1

In Winforms,
I have a non-GUI thread listening for incoming UDP messages.
When it receives a message, it update various UI components on a form by calling one of the form's methods.

This is apparently a race condition.
It seems that I am suppose to use some kind of InvokeIfRequired pattern on every single component.

Can I just get a single lock, instead of litering my code with hundreds of these InvokeIfRequired conditionals and lambdas everywhere that people seem to suggest? Can I introduce a thread safe adjustment around the single call to the form, instead of having to modify the internals of the form code?

My running thread looks something like this:

private static void HandleMessages(frmGui gui)
{
   while(true){
      if (/*udp message found*/){
          gui.UpdateLotsOfGuiComponents();
      }
   }
}

And the form looks something like this:

public partial class frmGui : Form
{
    public void UpdateLotsOfGuiComponents()
    {
        //lots of UI changes through a large call stack
    }
}

I was hoping to just put something around my call to gui.UpdateLotsOfGuiComponents();.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 2
    Yes, once you've Invoked() against the Form, you can update as many controls as you want in that call. – Idle_Mind Jan 06 '17 at 04:19
  • Can you point to article/post that suggest "littering with hundreds if(InvokeRequired)" calls? So far I have not seen anything of that kind (i.e. http://stackoverflow.com/questions/3874134/cleaning-up-code-littered-with-invokerequired or MSDN's [InvokeRequired](https://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired(v=vs.110).aspx) ) - all sources I've seen say you need to update controls on UI thread and to do that you should check for InvokeRequired (which searches up to parent form), there is no requirement to have each control to be checked updated separately. – Alexei Levenkov Jan 06 '17 at 04:20

0 Answers0