I have the class ComputationService which is the wrapper of the old legacy COM object. This COM object cannot have multiple instances because of how its implemented.
In the application, there are two buttons (for simplification) when clicked a new Task runs which use a ComputationService these tasks are kind of long-running tasks so you can click on the second button when the first one is in the process of computing. That's where the problem occurs because I can't let both threads use the ComputationService so I decided to use Mutex to allow only one instance of ComputationService at the time.
What I have:
public class ComputationService : IComputationService
{
public ComputationService()
{
_mutex = new Mutex(true, "AwesomeMutex");
_mutex.WaitOne();
}
public void Dispose()
{
_mutex.ReleaseMutex();
}
}
and then two places where I use it:
public Task Compute1()
{
return Task.Run(() =>
{
foreach (var item in items)
{
using (var service = _computationFactory()) // new instance of ComputationService
{
//Do some work
}
}
});
}
public Task Compute2()
{
return Task.Run(() =>
{
foreach (var item in items)
{
using (var service = _computationFactory()) // new instance of ComputationService
{
//Do some other work
}
}
});
}
What I get when I am debugging to console:
Mutex created by Thread: 18
Wait, thread: 18
Do Work, thread: 18
Mutex created by Thread: 20
Wait, thread: 20
Mutex release by thread: 18
Mutex created by Thread: 18
Wait, thread: 18
Do Work, thread: 18
Mutex release by thread: 18
Then of course AbandonedMutexException() occurs on Thread 20.
I tried to use lock in the constructor of ComputationService but did not work.
Can you please help me, what I am doing wrong and how to fix it?