Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is InvokeRequired required? [duplicate]

Tags:

c#

invoke

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);
    });
like image 576
user3398315 Avatar asked Dec 21 '25 01:12

user3398315


2 Answers

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().

like image 82
Marc Gravell Avatar answered Dec 22 '25 15:12

Marc Gravell


If you know for sure that the method will be called from a non-GUI thread there's no point in using InvokeRequired.

Furthermore, you could put that listbox1.Items.Add(Container.error_message); into a method (DRY - don't repeat yourself). That method could be called without InvokeRequired from the GUI and by Invoke from a background thread.

Finally, (if at all) the usual pattern would be like so:

void AddMessageToListBox(String message)
{
    if (listbox1.InvokeRequired)
    {
        listbox1.Invoke((Action<String>)AddMessageToListBox, message);
        return;
    }

    listbox1.Items.Add(message);
}
like image 29
JeffRSon Avatar answered Dec 22 '25 15:12

JeffRSon