1

目前,我有一个从命名管道异步接收数据的 Windows 窗体。为避免出现“跨线程操作无效:从创建它的线程以外的线程访问的控件‘myTextBox’”,我正在使用匿名方法(请参阅http://www.codeproject.com/Articles/28485/ NET-Part-of-n 的初学者指南):

            // Pass message back to calling form
            if (this.InvokeRequired)
            {
                // Create and invoke an anonymous method
                this.Invoke(new EventHandler(delegate
                {
                    myTextBox.Text = stringData;
                }));
            }
            else
                myTextBox.Text = stringData;

我的问题是,“new EventHandler(delegate”) 行是做什么的?它会创建一个委托的委托吗?有人可以解释一下,我将如何使用命名委托来实现上述功能(只是为了帮助理解它) ? TIA。

4

1 回答 1

3

如果您有 C++ 背景,我会将委托描述为指向函数的简单指针。委托是 .NET 安全处理函数指针的方式。

要使用命名委托,您首先必须创建一个函数来处理事件:

void MyHandler(object sender, EventArgs e)
{
    //Do what you want here
}

然后,对于您之前的代码,将其更改为:

this.Invoke(new EventHandler(MyHandler), this, EventArgs.Empty);

如果我这样做,我会这样写以避免重复代码。

EventHandler handler = (sender, e) => myTextBox.Test = stringData;

if (this.InvokeRequired)
{
    this.Invoke(handler, this, EventArgs.Empty);  //Invoke the handler on the UI thread
}
else
{
    handler(this, EventArgs.Empty); //Invoke the handler on this thread, since we're already on the UI thread.
}
于 2014-05-01T22:34:59.110 回答