我的同事喜欢这样做

if (!listbox1.InvokeRequired)
    listbox1.Items.Add(Container.error_message);
else
    listbox1.Invoke((MethodInvoker)delegate
    {
        listbox1.Items.Add(Container.error_message);
    });

为什么他必须检查InvokeRequired?仅使用此语句会更好吗?
    listbox1.Invoke((MethodInvoker)delegate
    {
        listbox1.Items.Add(Container.error_message);
    });

最佳答案

如果您确信某个特定的路由只能由一个回调线程来访问,那么我倾向于同意您的意思-并不是为了避免Invoke而是为了避免任何重复。如果可以从多个路由到达路径,则最好进行检查以避免在非线程情况下产生任何开销,但是:进行重构,以使每个代码路径都知道它在做什么(只是调用一个实用程序方法)可能更可取,即UI线程仅调用Foo(),而工作线程使用Invoke / MethodInvoker调用Foo()

关于c# - 是否需要InvokeRequired?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24199412/

10-09 08:18