Click here to Skip to main content
15,877,915 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
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});
private void addToListview1(ListViewItem 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)?

Sergey Alexandrovich Kryukov 15-Jan-12 20:09pm    
This question is so correct that you almost don't need an answer. Nevertheless, I answered in detail (as it can interesting to other readers) and voted 5 for this question.


1 solution

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 function InvokeRequired — 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[^].

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900