Why ApplicationException is thrown?

Deadly 提交于 2019-12-08 16:45:36

You are releasing the mutex even if your WaitOne failed. Move the ReleaseMutex call inside the if statement where you know you have the mutex obtained.

@John's answer is correct but for posterity, I think a better pattern would be to set a boolean to be true in the if and then still do the release in the finally block but this time only do it if the boolean is true. The problem is that if any of the if clause throws then the mutex will not be released. I assume you will be adding more to the if clause than just a write and a sleep.

You always want to use a try { ... } finally pattern if you can, but just protect against the waitOne() call returning false. Something like the following:

bool release = false;
try {
    if (mut.waitOne(time)) {
        release = true;
        ...
    } else {
        ...
    }
} catch (AbandonedMutexException ex) {
    ...
} finally {
    ...
    if (release) {
        mut.ReleaseMutex();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!