I'm trying to detect whether the EzCad2 software is currently laser marking (mutex locked/signaled) or idle (mutex released/nonsignaled) using a publicly documented mutex. According to the documentation, such an approach is desired and possible.
Here is an excerpt:
"Option Enable Mark Mutex (EZCAD2MUTEX_MARKING): This option is used to synchronize the Ezcad program with third-party programs. If checked, the Ezcad software creates a mutex object named “EZCAD2MUTEX_MARKING”. The mark command cannot be executed until the mutex is 'signaled' by other programs. After marking, the mutex will be switched to 'nonsignaled' state by Ezcad software."
I want to achieve this with the following code:
private void Foo()
{
Mutex tmpMutex = null;
try
{
string mutexname = "EZCAD2MUTEX_MARKING";
if(!Mutex.TryOpenExisting(mutexname, out tmpMutex))
{
tmpMutex = new Mutex(true, mutexname, out bool createdNew);
}
while(true)
{
if(tmpMutex.WaitOne(1)) // Ezcad not marking
{
Console.Write("mutex free");
tmpMutex.ReleaseMutex(); // EzCad could mark after release
Console.WriteLine(" + released successfully");
}
else
{
Console.WriteLine("mutex blocked"); // EzCad is Marking
}
Thread.Sleep(50); // Wait for a Bit before next round
}
}
catch
{
throw;
}
finally
{
if(tmpMutex != null)
{
tmpMutex.Wait();
tmpMutex.ReleaseMutex();
tmpMutex.Close();
tmpMutex.Dispose();
}
}
}
For unexplained and non-reproducible reasons, EzCad stops responding after several iterations. My program remains in the "mutex free" branch. Either the mutex is not being released by tmpMutex.ReleaseMutex()
or EzCad is not taking the mutex anymore.
Now the Catch at which point i think there's a logic error in my code: EzCad stays in that state forever if my Software is still running. Once i kill my software, EzCad starts to continue as normal.
Does my program have any obvious logic errors?
I tried following things:
EDIT
With that, I've seen the same behavior as EzCad, which is that my main programm isn't responding (Unable to execute WaitOne(0) successfully - and so isn't able to reclaim the mutex) even though I executed ReleaseMutex on my simulation helper.
If I Kill the helper my main software returns back to normal just like EzCad does. So I im pretty shure something about the execution or use of "ReleaseMutex" Method is wrong even though it's executed without throwing a exception.
ORIGINAL APROACH ABANDONED
I now abandoned the Mutex aproach, since I found another, easier method of checking for EzCad's cctivity.
I'm sure the Code of @RalfBas Visscher should work.
I did finally realize that Mutex really isn't meant to be used like this. Its real use is to provide threadsave access to resources, not to check for other programs activity.
For those who may be interested in the new approach: I used a empty text-Object in Database with output set to a .txt file. Once this file exists, I know EzCad started marking. And delete it after a given time (const int timeMs for each individual object)