3

I have a counter - let's just call it : ItemsRemaining.

I will have a dynamic amount of threads, but for this example, let's say I have 10 threads.....

each thread will contain a loop, and each iteration in the loop does a unit of work, then should update the ItemsRemaining variable on GUI thread. This could be a private int, or it could even be a control value.

How can I accurately update this ItemsRemaining from multiple thread calls? While at the same time not taking too big a performance knock from locking?

nvoigt
  • 75,013
  • 26
  • 93
  • 142
JL.
  • 78,954
  • 126
  • 311
  • 459
  • could you create a static class that controls the number of units remaining and handles any incoming changings. then each thread could just raise an event, the controlling class can then just work through all the incoming events. – SmithMart Jul 15 '13 at 07:42

4 Answers4

2

You should check the methods from the Interlocked class.

Florin Dumitrescu
  • 8,182
  • 4
  • 33
  • 29
  • That's what I wanted to write, but then I noticed the `GUI` part. – Nolonar Jul 15 '13 at 07:43
  • Updating a variable used by UI using Interlocked is fine. If code also needs to be run in order to update the UI itself, then the variable can be updated with Interlocked and the UI updated with [Form.Invoke](http://stackoverflow.com/questions/4928195/c-sharp-windows-forms-application-updating-gui-from-another-thread-and-class). – Florin Dumitrescu Jul 15 '13 at 07:51
0

I believe locking is the fastest way of synchronizing two threads. If you're already using that, you should be good.

Pranav Negandhi
  • 1,594
  • 1
  • 8
  • 17
0

You could use a simple lock or Interlocked.Decrement. I don't think locking anything will be a performance hit, if any of your threads is worth creating in the first place.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • 1
    Related to locks, it is not the locks themselves that can cause a performance hit, but rather the lock contention, since it might decrease the degree of parallelism achieved by the application. If Interlocked can be used instead of locks, it should be the first choice. – Florin Dumitrescu Jul 15 '13 at 08:25
0

If you are going to update UI on each increment of the variable, then call the method which updates the UI using Control.Invoke (Winforms) or Dispatcher.Invoke (WPF) from your threads - and increment the int variable in that method itself right before you update the UI. That way no locking is required because modification to variable is automatically synchronized over UI thread.

You can also use the BeginInvoke variants if you don't want to hold your worker threads to wait till UI update is complete.

YK1
  • 7,327
  • 1
  • 21
  • 28