I have a problem concerning the System.Threading
Microsoft .NET namespace. In this namespace, many classes are defined in order to help me managing with threads. Well, I have a problem, but I do not know what to use, MSDN is vague and I still haven't got a clue of what classes do what. in particular, my problem concerns synchronization.
I have a certain number of threads (consider N threads). At a certain point a thread must stop and wait for at least one of the other thread to do something. Once one of the N - 1 threads has done a certain task, this thread notifies and the stopped thread will be able to proceed.
So it is just a synchronization issue: a thread must wait to be signalled, that's all.
In System.Threading
there are many classes provided in order to handle synchronization issues. There are WaitHandle
(s), there are AutoResetEvent
(s), there are ManualResetEvent
(s) and so on...
Which one whould I use?
My question is: can anybody summarize me which class I should use in order to solve my problem? Could you please tell the most important differences between these classes, or other classes?
The point is that I havn't really understood what class is responsible of in the synchronization matter: what is the difference, for example, between a WaitHandle
and an AutoResetEvent
or ManualResetEvent
?
In order to handle many threading issue, .net provides lock
functionalities and the Monitor
class. Is this couple good for my needs?
Thankyou
Mutex, event, conditional variables and semaphores are all synchronization primitives.
Synchronization is a concept that is used to prevent multiple threads from accessing a shared resource concurrently. You can use it to prevent multiple threads from invoking the properties or methods of an object concurrently.
Synchronization is a technique that allows only one thread to access the resource for the particular time. No other thread can interrupt until the assigned thread finishes its task. In multithreading program, threads are allowed to access any resource for the required execution time.
Albahari's book is amazing, you should really read through it some time. Its grown alot lately!
You want an EventWaitHandle
(EWH), they are nice because there is nothing to pass around, they are used for signaling threads (either in the same or in a different process) and as the name implies, they can be waited on.
You would open one on the thread that is doing the waiting, you open it with a given name that the other thread is going to know about. Then you wait on that wait handle.
The signaling thread will open an existing wait handle of the same name (name is a string) and call set
on it.
AutoResetEvent
s and ManualResetEvent
s both inherit from EWH and they are really just EWH's, they just act differently. Which one you want just depends on if you want the EWH to act as a gate or a turnstyle. You only care about this if you are using the wait handle more than once or you are waiting on that wait handle by more than one thread. I've used wait handles a decent amount (I suppose) and I don't think I've ever used a Manual.
Whatever you do, dont pass an instance of a wait handle around, they are meant to be opened seperately by their own threads. The name you specify will ensure that they are the "same" wait handle.
If the threads are in different processes, then you will HAVE to prefix the name of the EWH with @"Global\"
, otherwise the names of the wait handles will be encapsulated within the same process. Alternatively, if you are using them all within the same process, dont use the global namespace. When you don't specify a prefix with a backslash, one is automatically added to keep it private, but you don't need to know that prefix.
Keep in mind that EWH's can be permissioned, and if you run into issues with that I reccomend that you use EventWaitHandleRights.FullControl
, but you can browse the full EventWaitHandleRights enumeration here.
I like to name my EWH's with a Guid.NewGuid().ToString("N")
(Guid.NewGuid & Guid.ToString). I typically do this when the signaling thread is created, since you can easily pass information to it at that time. So in that case, the initial thread creates the string and passes it to the signaling thread when its created. That way both threads know of the name, without having to do any fancy cross-thread passing of variables.
EWH implements IDisposable
so wrap it in a using
block
EWH's are nice because if for whatever reason the signaling thread opens and signals the wait handle before the waiting thread even creates it, everything will still work and the waiting thread will be signaled the instant it hits the wait.
Because of this, though, the thread that is waiting on it will need to have some error trapping because you will need to call OpenExisting
. If you call one of the ctor
's and the EWH is already opened, you'll get a UnauthorizedAccessException
or a WaitHandleCannotBeOpenedException
thrown as described here, under Exceptions. You'll still be able to open that EWH and get the functionality you need, you may just have to open it instead of create it.
The difference between an auto-reset event and a manual-reset event is that an auto-reset event clears itself (closes) after one use, so only one item gets through the gate. I suspect an AutoResetEvent
would do nicely here. Personally I tend to use Monitor
more, though - it has lower overheads, but you do need to be a bit careful; your first thread must be sure to own the lock before any of the others, i.e
object lockObj = new object(); lock(lockObj) { // start the workers, making lockObj available to them Monitor.Wait(lockObj); }
with the workers doing something like:
// lots of work // now signal lock(lockObj) Monitor.Pulse(lockObj); // other work
Holding the lock originally means that we don't miss any messages while we are spinning up workers, as any workers getting to lock(lockObj)
will be blocked until the original thread releases the lock at Monitor.Wait
. The first thread the Pulse
will signal our original thread to continue.
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