Search code examples
c#multithreadingwcf

When does WaitOne execute non-framework code?


I experience race conditions leading to other code being executed during a call to System.Threading.WaitHandle.WaitOne, on the thread WaitOne is running on. From its documentation, I assumed that WaitOne blocks the thread for any non-framework code until one of its return conditions is met.

In what situations, if any, is WaitOne supposed to execute non-framework code before returning?


Sadly, I cannot determinate what method has been used to schedule the code that actually is executed in my case. However, I can still give some details:

  • An application outside of my control (Outlook) loads an unmanaged DLL, which calls a managed DLL, which calls a method on a WCF proxy. WCF's implementation calls WaitOne, during which call the issue occurs. This means that there are several unmanaged/managed transitions on the stack.
  • The WCF connection goes through a NetNamedPipeBinding, the target process has previously been started from the managed DLL.
  • During the WCF proxy invocation, Outlook gets a chance to execute code on the same thread. After that code execution, the invocation still finishes correctly.
  • I only observed this behavior on the main/ui thread
  • I only observed this behavior in 32 bit builds. 64 bit builds work as expected.
  • When moving all WCF calls to a different thread, and switching to explicit invocations of Task.Wait (on tasks created via Task.Run), the Wait presents the same behavior; it is thus likely that Monitor.Wait and other related methods behave in an equal way.

Solution

  • All waits in .NET are "alertable." This means that if a wait blocks, Windows can run "Asynchronous Procedure Calls" on top of the waiting stack.

    Nicholas Butler, excerpt from an answer to a different question linked by Timmy_A in the comments