为什么抛出AbandonedMutexException以及如何避免它?

时间:2013-02-26 14:17:09

标签: c# multithreading asynchronous synchronization mutex

以下c#控制台应用程序(从文章"Using Mutex and WaitOne with Threading in C# .Net"复制粘贴的代码)在完成之前抛出

  

AbandonedMutextException未处理   {“由于被遗弃的互斥锁而等待完成。”} {“由于弃置的互斥锁导致等待完成。”}

就行:

static Mutex mutex = new Mutex(false);  

传递最后一行后阻止控制台输入:

Console.ReadLine();

有什么问题以及如何纠正?

using System;
using System.Threading;

class Database
{
  static Mutex mutex = new Mutex(false);

  public static void SaveData(string text)
  {
    mutex.WaitOne();
    Console.WriteLine("Database.SaveData - Started");
    Console.WriteLine("Database.SaveData - Working");
    for (int i = 0; i < 100; i++)
    {
      Console.Write(text);
    }
    Console.WriteLine("\nDatabase.SaveData - Ended");
    mutex.Close();
  }
}

class ThreadMutexApp
{
  public static void WorkerThreadMethod1()
  {
    Console.WriteLine("Worker thread #1 - Started");
    Database.SaveData("x");
    Console.WriteLine("Worker thread #1 - Returned from Output");
  }

  public static void WorkerThreadMethod2()
  {
    Console.WriteLine("Worker thread #2 - Started");
    Database.SaveData("o");
    Console.WriteLine("Worker thread #2 - Returned from Output");
  }

  public static void Main()
  {
    ThreadStart worker1 = new ThreadStart(WorkerThreadMethod1);
    ThreadStart worker2 = new ThreadStart(WorkerThreadMethod2);

    Console.WriteLine("Main - Creating worker threads");

    Thread t1 = new Thread(worker1);
    Thread t2 = new Thread(worker2);

    t1.Start();
    t2.Start();

    Console.ReadLine();
  }
}

1 个答案:

答案 0 :(得分:2)

首先进入SaveData()的线程,关闭静态互斥锁并使其无法用于第二个。 mutex.Close();应替换为mutex.ReleaseMutex();

引用MSDN

  

使用此方法释放实例所拥有的所有资源   WaitHandle的。调用此方法后,引用当前   实例导致未定义的行为