0

我有这些代码行:

// index is an integer
Mutex mutex = new Mutex(false, "MUTEX_PREFIX" + index.ToString());
mutex.WaitOne();
// Access to the shared object which should not be accessed by multiple threads.
mutex.ReleaseMutex();

其他线程使用相同的逻辑(称为互斥锁),因此我确保将正确的锁用于正确的资源。

问题是如果命名mutex被另一个线程(或进程)获取,当前线程会得到一个异常而不是在第二行被阻塞。

我需要的是等待一个命名mutex被释放,然后继续我的代码。

我哪里错了?

4

1 回答 1

0

完成后,您必须调用 mutex.ReleaseMutex()。您还可以捕获所有异常并释放和重新抛出;

一个典型的模式是使用锁,它处理异常:

 lock (typeof(MyClass))
 {
     .. access to the share object
 }
于 2011-04-11T01:53:59.877 回答