是否需要InvokeRequired?

use*_*315 2 c# invoke

我的同事喜欢这样做

if (!listbox1.InvokeRequired)
    listbox1.Items.Add(Container.error_message);
else
    listbox1.Invoke((MethodInvoker)delegate
    {
        listbox1.Items.Add(Container.error_message);
    });
Run Code Online (Sandbox Code Playgroud)

他为什么要检查InvokedRequired?仅使用此声明会更好吗?

    listbox1.Invoke((MethodInvoker)delegate
    {
        listbox1.Items.Add(Container.error_message);
    });
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

如果您确信某个特定路由只能通过回调线程达到,那么我倾向于同意您的意见 - 不是为了避免这种情况Invoke,而是为了避免任何重复.如果可以从多个路由到达路径,则可能最好进行检查以避免非线程情况下的任何开销,但是:重构以便每个代码路径知道它在做什么(只是调用实用程序方法)可能是优选的,即UI线程只是调用Foo(),其中工作线程使用Invoke/ MethodInvoker调用Foo().