Home Is the Mutex class safe to use within an ASP.NET request?
Reply: 1

Is the Mutex class safe to use within an ASP.NET request?

Sam.Rueby
1#
Sam.Rueby Published in 2017-11-14 22:12:48Z

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.

John Wu
2#
John Wu Reply to 2017-11-14 23:35:09Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.318563 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO