C# 在C中,用互斥锁锁定进一步执行的线程,并从其他线程和类打开它#
我有一个C# 在C中,用互斥锁锁定进一步执行的线程,并从其他线程和类打开它#,c#,multithreading,mutex,C#,Multithreading,Mutex,我有一个Form1类和一个OtherThreadClass。在OtherThreadClass中,我想传输一些数据,并在每次传输后等待接收。接收事件由Form1处理 现在,我已经考虑过使用互斥,因为这似乎适合我的任务。使用mutex.ReleaseMutex()执行时,Form1中的接收方法应解锁myThread 因此,对于测试,从表格1中我知道 public static Mutex mutex = new Mutex(); Thread myThread; public Form1()
Form1
类和一个OtherThreadClass
。在OtherThreadClass
中,我想传输一些数据,并在每次传输后等待接收。接收事件由Form1
处理
现在,我已经考虑过使用互斥,因为这似乎适合我的任务。使用mutex.ReleaseMutex()
执行时,Form1
中的接收方法应解锁myThread
因此,对于测试,从表格1
中我知道
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 buy启动应用程序
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
发布之后等待完成。
我在这里做错了什么,应该如何做李>
Threadclass中\u互斥体的初始化也可能是一个问题。因为它没有被使用,也不会被发布,只是被覆盖,所以它可能会在系统中悬空。不要初始化互斥锁。不要使用
互斥锁
它们很昂贵。使用Monitor。输入
和Monitor。退出
instead看起来你想要的是一个信号灯
。好的,我会同时查看这两个。谢谢你不要使用互斥锁,它们很贵。使用Monitor。输入
和Monitor。退出
instead看起来你想要的是一个信号灯
。好的,我会同时查看这两个。非常感谢。