我有一个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.
我在这里做错了什么,应该怎么做? 答案 0 :(得分:1)
Threadclass中的_mutex初始化也可能是个问题。因为它没有被使用而且不会被释放但只是被覆盖它可能在系统中悬空。不要初始化_mutex。