Reputation: 2802
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();
}
OtherThreadClass
pops up. Why is this? I thought the WainOne()
should wait until MutexRelease
was issued.The wait completed due to an abandoned mutex.
What am I doing wrong here, and how should this be done? Upvotes: 1
Views: 98
Reputation: 1362
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