尝试获取先前获取的互斥锁时出现异常
我有以下几行代码:
// 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();
其他线程使用相同的逻辑(称为互斥体),因此我确保将正确的锁用于正确的资源。
问题是,如果另一个线程(或进程)获取了指定的互斥锁,则当前线程会出现异常,而不是在第二行被阻塞。
我需要的是等待一个命名的互斥体被释放,然后继续我的代码。
我哪里错了?
I have these lines of code:
// 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();
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
完成后您必须调用 mutex.ReleaseMutex() 。您还可以捕获所有异常并释放和重新抛出;
典型的模式是使用锁来处理异常:
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: