Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the exit context mean for a WaitHandle.WaitOne mean?

I'm trying to use a mutex to protect access to some hardware from multiple threads, but I'm confused as to what the exitContext parameter means / does:

public virtual bool WaitOne (
    int millisecondsTimeout,
    bool exitContext
)

The docs say:

exitContext - true to exit the synchronization domain for the context before the wait (if in a synchronized context), and reacquire it afterward; otherwise, false.

...but what does that actually mean and what are the consequences of setting it to either true or false? I've set it to true for now and the code appears to work, but I'm nervous that I don't fully understand what it's up to under the hood!

like image 370
Jon Cage Avatar asked Oct 19 '11 16:10

Jon Cage


People also ask

What does WaitOne do?

WaitOne(TimeSpan, Boolean) Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait.

How to use WaitHandle in c#?

static WaitHandle[] waitHandles = new WaitHandle[] { new AutoResetEvent(false), new AutoResetEvent(false) }; // Define a random number generator for testing. static Random r = new Random(); static void Main() { // Queue up two tasks on two different threads; // wait until all tasks are completed.


1 Answers

The Remark section of MSDN page reads like utter gobbledegook of course. Execution contexts are a well-hidden implementation detail in .NET. I'll just tell you what I reversed engineered without being able to completely nail it down.

The exitContext argument is relevant in remoting scenarios only. By passing true, you allow the current call to be suspended and another call to be marshaled from the client to the server. You'd do so to improve throughput, selecting true only when you expect the WaitOne() call to take a while. The exact implications of doing so are however not obvious to me, nor documented anywhere I know of. The WaitOne() overload (no timeout) always passes false, that puts some strain on my explanation unfortunately.

A side-story behind this method is that it is so poorly understood that Microsoft decided to break backward compatibility in .NET 2. They added the WaitOne(int) overload in service pack 2. Which passes false for the exitContext argument. This caused a lot of mayhem, programmers started using it then found their program to fail when run on a pre-SP2 version of .NET. Ouch.

like image 157
Hans Passant Avatar answered Oct 10 '22 18:10

Hans Passant