4

The Mutex documentation states:

The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity. A mutex can also be passed across application domain boundaries.

ASP.NET implements thread agility, meaning:

... IIS is free to use more than one thread to handle a single request, although not in parallel.

If these two statements are true, then it must be unsafe to use the Mutex class from within an ASP.NET request, because a request can be processed by multiple threads and a mutex can only be released by the thread that acquired it.

Despite this, I can't find it written anywhere that Mutex cannot be used within an ASP.NET request.

Sam Rueby
  • 5,914
  • 6
  • 36
  • 52
  • i am pretty confident that if you are not using `async`, `Thread` or TPL apis, and thus your control is passed synchronously, it will be the same thread serving the same request. you should, of course, release mutex before returning result from asp.net. – zaitsman Nov 14 '17 at 22:15
  • 2
    Depending on when you allocate your mutex during the processing of a request, it's possible that IIS migrates the request from one thread to another. It's not guaranteed that a single request will be handled by a single thread. This is what "thread agility" means. It's not safe to use a Mutex for this scenario - anything that assumes a particular thread in ASP.NET (or in async code) is unsafe. – xxbbcc Nov 14 '17 at 23:17

1 Answers1

3

Under thread agility, ASP.NET may use a different thread for different handler calls. It's rare. But occasionally you'll see that your module's BeginRequest handler executed on a different thread from the page's OnPreRender handler, that sort of thing.

If you're using a using clause and creating and disposing of the Mutex within the same method call, you will probably be fine.

If for whatever reason the thread does switch on you, the mutex will be treated as abandoned and any other thread can acquire it (WaitOne()) at that point.

John Wu
  • 50,556
  • 8
  • 44
  • 80
  • do you have any data to backup your answer? The ASP.NET under thread-agility is switching native threads or is switching managed threads? How can we simulate this behavior? – Pedro Simões Dec 13 '17 at 20:10