从另一个线程发送winforms通知popup窗口

我在我的基本聊天程序中遇到了一个独特的小错误,它声明我不能从另一个线程发送一个Notification Popup :

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. 

当我调用popupNotification.Popup(); 从这个方法:

 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 + "\""); } 

我试图创build应该看起来像这样的跨线程代码:

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

但是,通知popup窗口库没有Invoke Required方法,所以我运气不好。

谁能帮忙?

Solutions Collecting From Web of "从另一个线程发送winforms通知popup窗口"

方法有点不同于重复,所以我想我把它们放在这里之前,把它们标记为重复。

以下是解决这个问题的方法:

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