在 ASP.NET 请求中使用 Mutex class 是否安全?
Is the Mutex class safe to use within an ASP.NET request?
Mutex 文档指出:
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实现了thread agility,意思是:
... IIS is free to use more than one thread to handle a
single request, although not in parallel.
如果这两个陈述成立,那么在 ASP.NET 请求中使用互斥体 class 一定是不安全的,因为一个请求可以由多个线程处理,而互斥体只能由获取它的线程释放。
尽管如此,我找不到在 ASP.NET 请求中不能使用 Mutex 的地方写的。
在线程敏捷性下,ASP.NET 可以为不同的处理程序调用使用不同的线程。很少见。但偶尔您会看到您的模块的 BeginRequest 处理程序在与页面的 OnPreRender 处理程序不同的线程上执行,诸如此类。
如果您使用 using
子句并在同一方法调用中创建和处理 Mutex,则可能没问题。
如果线程出于某种原因确实打开了您,则互斥量将被视为已放弃,此时任何其他线程都可以获取它 (WaitOne()
)。
Mutex 文档指出:
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实现了thread agility,意思是:
... IIS is free to use more than one thread to handle a single request, although not in parallel.
如果这两个陈述成立,那么在 ASP.NET 请求中使用互斥体 class 一定是不安全的,因为一个请求可以由多个线程处理,而互斥体只能由获取它的线程释放。
尽管如此,我找不到在 ASP.NET 请求中不能使用 Mutex 的地方写的。
在线程敏捷性下,ASP.NET 可以为不同的处理程序调用使用不同的线程。很少见。但偶尔您会看到您的模块的 BeginRequest 处理程序在与页面的 OnPreRender 处理程序不同的线程上执行,诸如此类。
如果您使用 using
子句并在同一方法调用中创建和处理 Mutex,则可能没问题。
如果线程出于某种原因确实打开了您,则互斥量将被视为已放弃,此时任何其他线程都可以获取它 (WaitOne()
)。