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();
}
- 第一次左右,從
OtherThreadClass
提示消息兩者彈出。爲什麼是這樣?我認爲WainOne()
應該等到MutexRelease
發佈。 - 下一次我開始執行,我得到
The wait completed due to an abandoned mutex.
我在這裏做錯了什麼,以及應該怎麼做?
不要使用'Mutex',它們很貴。使用'Monitor.Enter'和'Monitor.Exit'代替 –
看起來你想要的是一個'Semaphore'。 – Servy
奧基,我會看着兩個。謝謝 – chwi