开发者

Exception on trying to acquire a previously acquired mutex

I have these lines of code:

// index is an integer
Mutex mutex = new Mutex(false, "MUT开发者_如何学编程EX_PREFIX" + index.ToString());
mutex.WaitOne();
// Access to the shared object which should not be accessed by multiple threads.
mutex.ReleaseMutex();

The same logic (named mutex) is used by other threads, so I make sure the right lock is used for the right resource.

The problem is if the named mutex is acquired by another thread (or process), current thread gets an exception instead of get blocked on the second line.

What I need is waiting for a named mutex to be released and then continue with my code.

Where am I wrong?


You must call mutex.ReleaseMutex() when done. Also you catch all exceptions and release and the rethrow;

A typical pattern is to use lock, which copes with exceptions:

 lock (typeof(MyClass))
 {
     .. access to the share object
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜