我有一个Form1
班级和一个OtherThreadClass
. 在OtherThreadClass
我想传输一些数据,并在每次传输后等待接收。接收事件由 处理Form1
。
现在,我已经研究过使用互斥锁,因为这似乎适合我的任务。中的接收方法应该在执行时Form1
解锁.myThread
mutex.ReleaseMutex()
所以为了测试,从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.
我在这里做错了什么,应该怎么做?