从另一个线程

时间:2015-07-07 13:54:09

标签: c# windows multithreading 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 + "\"");
    }

我试图创建应该如下所示的跨线程代码:

public delegate void UpdatePopup(PopupNotifier notificationPopup);

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

但是,通知弹出窗口库没有Invoke Required方法,所以我对该修复程序运气不佳。

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

这些方法与副本有点不同,所以我想把它们放在这里,然后再将它们标记为副本。

以下是解决此问题的方法:

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