Sending a notification popup in winforms from another thread [duplicate]

∥☆過路亽.° 提交于 2019-12-11 16:29:44

问题


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?


回答1:


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;
        }
    }


来源:https://stackoverflow.com/questions/31270559/sending-a-notification-popup-in-winforms-from-another-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!