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);
});
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().
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With