【问题标题】:How does EventHandler with anonymous methods work?带有匿名方法的 EventHandler 是如何工作的?
【发布时间】:2014-05-01 22:24:13
【问题描述】:

目前,我有一个从命名管道异步接收数据的 Windows 窗体。为避免出现“跨线程操作无效:从创建它的线程以外的线程访问的控件‘myTextBox’”,我使用了匿名方法(请参阅http://www.codeproject.com/Articles/28485/Beginners-Guide-to-Threading-in-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。

【问题讨论】:

    标签: c# multithreading delegates eventhandler


    【解决方案1】:

    如果您有 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.
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      相关资源
      最近更新 更多