1

I've run into a unique little error in my basic chat program which states that I cannot send a Notification Popup from another thread:

An exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll but was not handled in user code

Additional information: Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.

This occurs when I call popupNotification.Popup(); from this method:

void ChatServer_OnDataReceived(object sender, ReceivedArguments e)
    {
        string machine = e.Name;
        string message = e.ReceivedData;
        popupNotification.TitleText = "New  message";
        popupNotification.ContentText = machine + " sent a message at " + DateTime.Now.ToShortTimeString() +
            ", saying  \"" + message + "\"";
        popupNotification.Popup();
        changeTextBoxContents(e.Name + " sent a message at " + DateTime.Now.ToShortTimeString() +
            ", saying  \"" + e.ReceivedData + "\"");
    }

I'm trying to create the cross-thread code which should look like this:

public delegate void UpdatePopup(PopupNotifier notificationPopup);

void sendAPopup(PopupNotifier notificationPopup)
    {
        if (notificationPopup.InvokeRequired)
        {
            Invoke(new UpdatePopup(sendAPopup), new object[] { notificationPopup });
        }
        else
        {
            notificationPopup.Popup();
        }
    }

However, the notification popup window library doesn't have a Invoke Required method, so I'm out of luck on that fix.

Can anyone help?

gtnewhouse
  • 29
  • 1
  • 6

1 Answers1

0

The methods are a bit different than the duplicate so I figured I put them here before marking them as a duplicate.

Here's how this issue is fixed:

void ChatServer_OnDataReceived(object sender, ReceivedArguments e)
    {
        string machine = e.Name;
        string message = e.ReceivedData;
        popupNotification.TitleText = "New  message";
        popupNotification.ContentText = machine + " sent a message at " + DateTime.Now.ToShortTimeString() +
            ", saying  \"" + message + "\"";
        popupMethod(); //call the method that works cross-thread
        changeTextBoxContents(e.Name + " sent a message at " + DateTime.Now.ToShortTimeString() +
            ", saying  \"" + e.ReceivedData + "\"");
    }
///This method works cross thread by checking if an invoke is required
///and if so, then the popup is shown with a delegate across the thread
void popupMethod()
    {
        if(InvokeRequired)
        {
            this.Invoke(new MethodInvoker(delegate {
                popupNotification.Popup();
            }));
            return;
        }
    }
gtnewhouse
  • 29
  • 1
  • 6