'What is the exitContext used for on a WaitHandle.WaitOne method
Example
System.Threading.AutoResetEvent e = new System.Threading.AutoResetEvent(false);
bool b = e.WaitOne(1000, false);
I've done a lot of multi threaded development in my time and have always wondered what the use of the that method was for. The second boolean parameter on the WaitOne is called exitContext. MS Help states "true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it afterward; otherwise, false."
Anyone any idea what this means? Is it something I should be worried about?
Kind Regards Noel
Solution 1:[1]
I can't claim credit (hence wiki) but there is a good answer here.
From the link, answer to the question, by Sasha Goldshtein
The CLR has support for a notion called contexts. A context is a logical grouping of objects. When a method call is made on an object that is inside your context, nothing in particular happens except for the method itself. When a method call is made on an object that is outside your context, then "something" might happen before the method itself is executed. All .NET classes derived from ContextBoundObject will be associated with a context at runtime.
An example of that "something" that can happen before the method is called would be enforcing synchronization. An object that derives from ContextBoundObject and specifies the [Synchronization] attribute will get automatic synchronization services from the runtime. This means that only one thread will ever be able to execute within the object's context.
The exitContext parameter of the WaitOne method specifies whether to leave the synchronization context before issuing the wait. This enables reentrancy. Here's a scenario where this is necessary:
Code Snippet [Synchronization] public class MyCounter : ContextBoundObject {
private int _expectedCounterVal; private int _currentCounterVal; private ManualResetEvent _event = new ManualResetEvent(false);
public void WaitUntilCounterIs(int counterVal) {
_expectedCounterVal = counterVal; _event.WaitOne(TimeSpan.FromDays(1), true); }public void IncrementCounter() { if (++_currentCounterVal >= _expectedCounterVal) { _event.Set(); } } }
In this case, if the WaitUntilCounterIs method is issued without the exitContext=true parameter of the WaitOne method, then no other thread will be able to ever call the IncrementCounter method on the object, resulting in a deadlock. However, once exitContext=true is specified, other threads can enter the IncrementCounter method and signal the event at some point, even though the WaitUntilCounterIs method has not yet returned.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
