2013-09-25 18 views
1

我有Form1類和OtherThreadClass。在OtherThreadClass我想傳輸一些數據,並在每次傳輸後等待接收。接待活動由Form1負責處理。鎖定線程與進一步執行mutex並打開它從其他線程和類在C#

現在,我研究了使用互斥鎖,因爲這看起來適合我的任務。 Form1中的接收方法應在mutex.ReleaseMutex()執行時解鎖myThread

所以進行測試,從Form1我做

public static Mutex mutex = new Mutex(); 
Thread myThread; 


public Form1() 
{ 
    InitializeComponent(); 
    myThread = new Thread(threadedFunction); 
    myThread.Name = String.Format("Thread{0}", 0); 
    Thread.CurrentThread.Name = "mainThread"; 
} 

public void threadedFunction() 
{ 
    OtherThreadClass newThread = new OtherThreadClass(mutex); 
    newThread.RunThread(); 
} 

OtherThreadClass

class OtherThreadClass 
{ 
    Mutex _mutex = new Mutex(); 

    public OtherThreadClass(Mutex mutex) 
    { 
     _mutex = mutex; 
    } 

    public void RunThread() 
    { 
    // Wait until it is safe to enter. 
     _mutex.WaitOne(); 

     MessageBox.Show(String.Format("{0} has entered the protected area", 
      Thread.CurrentThread.Name)); 
     _mutex.WaitOne(); 
     // Simulate some work. 
     Thread.Sleep(500); 

     MessageBox.Show(String.Format("{0} is leaving the protected area\r\n", 
      Thread.CurrentThread.Name)); 
     _mutex.ReleaseMutex(); 
    } 

} 

我開始從GUI的應用買按下按鈕。

private void button1_Click(object sender, EventArgs e) 
    { 
     if (!myThread.IsAlive) 
     { 
      myThread = new Thread(threadedFunction); 
      myThread.Name = String.Format("Thread{0}", 0); 
      myThread.Start(); 
     } 
    } 

爲了模擬接收方法我添加一個按鈕

private void button2_Click(object sender, EventArgs e) 
    { 
     mutex.ReleaseMutex(); 
    } 
  1. 第一次左右,從OtherThreadClass提示消息兩者彈出。爲什麼是這樣?我認爲WainOne()應該等到MutexRelease發佈。
  2. 下一次我開始執行,我得到The wait completed due to an abandoned mutex.我在這裏做錯了什麼,以及應該怎麼做?
+0

不要使用'Mutex',它們很貴。使用'Monitor.Enter'和'Monitor.Exit'代替 –

+0

看起來你想要的是一個'Semaphore'。 – Servy

+0

奧基,我會看着兩個。謝謝 – chwi

回答

1
  1. 第一WaitOne的互斥體是由你的線程另一個改變的WaitOne獲得性無關,因爲沒有其他線程在同時捕獲它之後。
  2. ReleaseMutex必須由互斥量已被獲取的線程調用。如果您的線程獲得了線程,則必須調用ReleaseMutex。

Thread類中初始化of_mutex可能也是個問題。由於它沒有被使用,並且不會被釋放,而是被覆蓋,所以它可能在系統中懸而未決。不要初始化_mutex。

相關問題