使用C#MethodInvoker.Invoke()获取GUI应用程序......这样好吗?

Sté*_*écy 26 c# multithreading invoke c#-2.0

使用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();
}
Run Code Online (Sandbox Code Playgroud)

通过使用这种模式,我不会复制实际的UI代码,但我不确定的是这种方法是否合适.

特别是这条线

method.Invoke()
Run Code Online (Sandbox Code Playgroud)

它是否使用另一个线程进行调用,或者它是否有点转换为直接调用GUI线程上的方法?

CMe*_*rat 21

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

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


Ste*_*yer 15

我个人喜欢这种方法:

private void ExecuteSecure(Action a)
{
    if (InvokeRequired)
        BeginInvoke(a);
    else
        a();
}
Run Code Online (Sandbox Code Playgroud)

然后你可以写这样的单行:

ExecuteSecure(() => this.Enabled = true);
Run Code Online (Sandbox Code Playgroud)


Gre*_*egC 5

请记住,如果您在后台线程AND Control.IsHandleCreated为false,则Control.InvokeRequired返回false.我会用Debug.Assert保护代码,检查非托管句柄的创建.