我的同事喜欢这样做
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().
更多推荐
发布评论