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
    发布之后
  • 下一次开始执行时,由于一个被放弃的互斥锁,
    等待完成。
    我在这里做错了什么,应该如何做
  • 在第一个WaitOne之后,互斥锁由您的线程获取,而另一个WaitOne不会更改任何内容,因为在此期间没有其他线程捕获它
  • 释放互斥体必须由获取互斥体的线程调用。如果它是由你的线程获得的,你的线程必须调用ReleaseMutex Threadclass中\u互斥体的初始化也可能是一个问题。因为它没有被使用,也不会被发布,只是被覆盖,所以它可能会在系统中悬空。不要初始化互斥

  • 在第一个WaitOne之后,互斥锁由您的线程获取,而另一个WaitOne不会更改任何内容,因为在此期间没有其他线程捕获它
  • 释放互斥体必须由获取互斥体的线程调用。如果它是由你的线程获得的,你的线程必须调用ReleaseMutex
    Threadclass中\u互斥体的初始化也可能是一个问题。因为它没有被使用,也不会被发布,只是被覆盖,所以它可能会在系统中悬空。不要初始化互斥锁。

    不要使用
    互斥锁
    它们很昂贵。使用
    Monitor。输入
    Monitor。退出
    instead看起来你想要的是一个
    信号灯
    。好的,我会同时查看这两个。谢谢你不要使用互斥锁,它们很贵。使用
    Monitor。输入
    Monitor。退出
    instead看起来你想要的是一个
    信号灯
    。好的,我会同时查看这两个。非常感谢。