是否需要InvokeRequired?(Is InvokeRequired required?)

编程入门 行业动态 更新时间:2024-10-26 02:24:59
是否需要InvokeRequired?(Is InvokeRequired required?)

我的同事喜欢这样做

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

为什么他必须检查InvokedRequired? 仅仅使用这个陈述会更好吗?

listbox1.Invoke((MethodInvoker)delegate { listbox1.Items.Add(Container.error_message); });

My coworker likes to do this

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

Why do he have to check for InvokedRequired? Will it be better to just use this statement only?

listbox1.Invoke((MethodInvoker)delegate { listbox1.Items.Add(Container.error_message); });

最满意答案

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

If you are confident that a particular route can only be reached by a callback thread, then I'd be inclined to agree with you - not really for the purpose of avoiding the Invoke, but simply to avoid any duplication. If a path can be reached from multiple routes, it may be preferable to have the check to avoid any overheads in the non-threaded case, but: refactoring so that each code-path knows what it is doing (just calling a utility method) may be preferable, i.e. the UI thread just calls Foo(), where as the worker thread uses Invoke / MethodInvoker to call Foo().

更多推荐

本文发布于:2023-08-05 15:15:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1433949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:InvokeRequired   required

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!