Mutex c#安全手柄已关闭

时间:2014-10-20 14:26:34

标签: c# .net mutex

这是我的方法调用相互扩散的代码

public class X
{
    private static Mutex mutex = new Mutex(true, "MutexForFile");
    public IList<string> DoIt(IList<string> documents)
    {
        var result = new List<string>();
        if (mutex.WaitOne())
        {
            using (var agent = new MyClass())
            {
                // operation login
                if (agent.LibraryLogon("**", "***"))
                {
                    try
                    {
                        //codes to access shared resource
                    }
                    catch (Exception e)
                    {
                        Log.ErrorFormat("");
                    }
                    finally
                    {
                        if (!mutex.SafeWaitHandle.IsClosed)
                        {
                            mutex.ReleaseMutex();
                        }
                        mutex.Dispose();
                    }
                    Log.DebugFormat("Completed");

                }
                else
                {
                    throw new Exception("Unable to Login Session");
                }
            }
            Log.DebugFormat("Completed Do it");
        }
        return result;
    }
}

我被迫检查 if(!mutex.SafeWaitHandle.IsClosed),因为我得到了ObjectDisposedException说&#34;安全句柄已经关闭&#34;当我调用mutex.ReleaseMutex()时。

是否是避免此异常的正确方法?

任何一次可以建议使用此代码的任何陷阱或问题吗?

1 个答案:

答案 0 :(得分:3)

当另一个线程正在等待它时,你应该避免丢弃互斥锁:

Thread #1: WaitOne() -> gets ownership
Thread #2: WaitOne() -> waits for thread #1
Thread #1: ReleaseMutex() -> causes thread #2 to continue
Thread #1: Dispose()
Thread #2: ReleaseMutex() -> mutex was disposed by thread #1

SafeWaitHandle.IsClosed只是防止出现异常,但无法解决根本问题。它只能在产生这些线程的代码中解决,而不是在线程内解决 - 也许你不应该有多个线程试图同时登录?