【发布时间】:2020-05-05 23:55:44
【问题描述】:
刚刚编写了一个必须一次处理一次的简单程序,因此通过使用带有特定名称的键控Mutex 来实现这一点。
代码(简化)如下所示。
static readonly string APP_NAME = "MutexSample";
static void Main(string[] args)
{
Mutex mutex;
try
{
mutex = Mutex.OpenExisting(APP_NAME);
// At this point, with no exception,
// the Mutex is acquired, so there is another
// process running
// Environment.Exit(1); or something
}
catch (WaitHandleCannotBeOpenedException)
{
// If we could not acquire any mutex with
// our app name, let's create one
mutex = new Mutex(true, APP_NAME);
}
Console.ReadKey(); // Just for keeping the application up
// At some point, I just want to release
// the mutex
mutex.ReleaseMutex();
}
我的第一次尝试是像 new Mutex(false, APP_NAME) 一样实例化 Mutex,但调用 mutex.ReleaseMutex() 会引发异常
System.ApplicationException: 'Object synchronization method was called from an unsynchronized block of code.'
刚刚注意到构造函数的第一个参数 (initiallyOwned) 标记了创建 Mutex 的当前线程是否拥有它,并且不出所料,线程无法释放不属于该线程的 Mutex .
因此,将此参数更改为 true 解决了该问题,如上面的代码所示。
好吧,我的问题是,该参数的全部意义是什么?我的意思是,我什么时候需要创建一个我无法发布的 Mutex。
而且,如果我将参数initiallyOwned 设置为false,谁真正拥有该Mutex?
谢谢。
【问题讨论】:
标签: c# .net concurrency mutex