chwi
chwi

Reputation: 2802

Lock thread with mutex from further execution and open it from other thread and class in C#

I have a Form1 class and an OtherThreadClass. In the OtherThreadClass I want to transfer some data, and wait for a reception after each transmission. The reception event is handled by Form1.

Now, I've looked into using mutex since this seems appropriate for my task. The reception method in Form1 should unlock the myThread upon execution with mutex.ReleaseMutex().

So for testing, from the Form1 I do

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();
}

and in 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();
    }

}

I start the application from gui buy pressing a button.

    private void button1_Click(object sender, EventArgs e)
    {
        if (!myThread.IsAlive)
        {
            myThread = new Thread(threadedFunction);
            myThread.Name = String.Format("Thread{0}", 0);
            myThread.Start();
        }
    }

To simulate the reception method I added a button

    private void button2_Click(object sender, EventArgs e)
    {
        mutex.ReleaseMutex();
    }
  1. First time around, both messageboxes from OtherThreadClass pops up. Why is this? I thought the WainOne() should wait until MutexRelease was issued.
  2. The next time I start the execution, I get The wait completed due to an abandoned mutex. What am I doing wrong here, and how should this be done?

Upvotes: 1

Views: 98

Answers (1)

Ralf
Ralf

Reputation: 1362

  1. After the first WaitOne the mutex is aquired by your thread another WaitOne changes nothing because no other thread has captured it in the meantime.
  2. ReleaseMutex must be called by the thread the mutex has been aquired from. If its aquired by your thread your thread must call ReleaseMutex.

The initialization of_mutex in your Threadclass might be a problem also. As it is not used and won't be released but just overwritten it might be dangling in the system. Don't initialize _mutex.

Upvotes: 1

Related Questions