有关Winform Control的多线程更新的最佳实践 [英] Best practices on multithread updates to winform control
本文介绍了有关Winform Control的多线程更新的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个从单独的监视线程更新的列表视图.这是使用以下标准调用方法更新的:
I have a listview that is updated from a separate monitoring thread. This is updated using the standard invoke method of:
private delegate void addListviewItem(ListViewItem lvItem);
private void someProcedure()
{
if (this.listView1.InvokeRequired)
{
var del = new addListviewItem(addToListview1);
listView1.Invoke(del, new object[] {tempLVI});
}else{
addToListview1(tempLVI);
}
}
private void addToListview1(ListViewItem lvItem)
{
listView1.Items.Add(lvItem);
}
所以,问题是:如果您知道总是将在单独的线程中调用它,那么您不能只说:
//这里有一些代码
So, question: If you know that this will always be called from a separate thread, can''t you just say:
//some code here
var del = new addListviewItem(addToListview1);
listView1.Invoke(del, new object[] {tempLVI});
???
前一种方法(测试是否需要调用)是否是避免不必要使用代理的开销的最佳实践(例如,如果您不确定自己可能在哪个线程上)?
谢谢!
???
Is the previous method (testing if invoke is required) just a best practice to prevent overhead with using a delegate unnecessarily (for example if you are not sure what thread you might be on)?
Thanks!
推荐答案
您绝对正确.仅在有时从UI线程(然后不再需要调用)和有时从某些非UI线程(无论哪种)调用的方法中需要InvokeRequired
.更常见的情况是创建仅从非UI线程调用的某些方法时.在这种情况下,无需检查谓词功能InvokeRequired
-始终需要它.您将节省一些CPU时间.
我在过去的答案中详细解释了调用在WPF和Forms中的工作方式:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
Treeview Scanner和MD5问题 [用于线程通信和线程间调用的简单阻塞队列 [ ^ ].
—SA
You are absolutely right.InvokeRequired
is only needed in methods which is called sometimes from the UI thread (and then invocation is never needed) and sometimes from some non-UI thread (no matter which). The more usual case is when you create some method only to be called from a non-UI thread. In this case, there is no need to check the predicate functionInvokeRequired
— it is always required. You will save some CPU time.
I explained in detail how invocation works in WPF and Forms in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].
As I was able to see, not everyone understands that without a UI thread this mechanism effectively does not work. Formally, invocation does not fail, but the behavior becomes trivial: the call is simply performed in the calling thread. :-(.
What to do in this case? For example, one can create a similar mechanism. Actually, I provided such code at CodeProject with detailed explanation and usage sample. In particular, you can queue delegate instances and use them in other thread. Please see my Tips & Trick article: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].
—SA
这篇关于有关Winform Control的多线程更新的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文