正在为GUI应用程序使用C#MethodInvoker.Invoke()。。。这个好吗?

正在为GUI应用程序使用C#MethodInvoker.Invoke()。。。这个好吗?,c#,multithreading,c#-2.0,invoke,C#,Multithreading,C# 2.0,Invoke,使用C#2.0和MethodInvoker委托,我有一个GUI应用程序从GUI线程或工作线程接收一些事件 我使用以下模式处理表单中的事件: private void SomeEventHandler(object sender, EventArgs e) { MethodInvoker method = delegate { uiSomeTextBox.Text = "some text"; }; if (InvokeRe

使用C#2.0和MethodInvoker委托,我有一个GUI应用程序从GUI线程或工作线程接收一些事件

我使用以下模式处理表单中的事件:

private void SomeEventHandler(object sender, EventArgs e)
{
    MethodInvoker method = delegate
        {
            uiSomeTextBox.Text = "some text";
        };

    if (InvokeRequired)
        BeginInvoke(method);
    else
        method.Invoke();
}
通过使用这种模式,我不会复制实际的UI代码,但我不确定的是,这种方法是否好

特别是这条线

method.Invoke()

它是否使用另一个线程进行调用,或者在某种程度上转换为对GUI线程上的方法的直接调用?

它在同一个线程上进行调用。您可以通过单步执行代码进行检查。这种方法没有错。

方法.Invoke()调用在当前执行线程上执行委托。使用
BeginInvoke(方法)
确保在GUI线程上调用委托


当可以从GUI线程和其他线程调用相同的方法时,这是避免代码重复的正确方法。

对于WinForms,调用
控件。调用(委托)
将消息发送到UI的thead消息泵。然后线程处理消息并调用委托。处理后,
Invoke
停止阻塞,调用线程继续运行代码。

请记住,如果您在后台线程,Control.InvokeRequired返回false,而Control.IsHandleCreated为false。我会用调试来保护代码。断言检查非托管句柄的创建。

我个人喜欢这种方法:

private void ExecuteSecure(Action a)
{
    if (InvokeRequired)
        BeginInvoke(a);
    else
        a();
}
然后你可以这样写一行:

ExecuteSecure(() => this.Enabled = true);

谢谢我一直坚持使用method.Invoke甚至Invoke((MethodInvoker)。回到BeginInvoke就成功了。这里有些不对劲。InvokeRequired对控件进行操作,您只是将它放在那里,而没有任何内容。这意味着什么?InvokeRequired与此相同。InvokeRequired。