Search code examples
c#.netthread-safetyinvokerequired

Multiple Invokes and thread safety


Lets assume that I have worker threads that increment a value on some control. Since an invoke is required, all the increments need to be done on the GUI thread. For that I use BeginInvoke.

My question is:

Can a race condition break the increment of the control, because multiple worker threads all invoked on the GUI thread simultaniously (and the increment itself someControl.Value += value; is obviously not atomic)?

Or to put it the opposite:

Is one Invoke guaranteed to be finished before another one will be handled?

delegate void valueDelegate(int value);

private void IncrementValue(int value)
{
   if (InvokeRequired)
   {
       BeginInvoke(new valueDelegate(IncrementValue),value);
   }
   else
   {
       someControl.Value += value;
   }
}

Thank you!


Solution

  • No, there's only one GUI thread - so you'll end up with the invoked delegates effectively being queued up to execute serially. If there were multiple GUI threads you would indeed have a race condition here - but you're fine with all the UI frameworks I'm aware of.