开发者

windows .net cross process synchronization

开发者 https://www.devze.com 2023-03-22 13:55 出处:网络
I need to do some cross process synchronization. Process B should do some actions only when Process A is running.

I need to do some cross process synchronization.

Process B should do some actions only when Process A is running. I tried using Mutex and EventWaitHandles like this :

In Process A main:

EventWaitHandle eventWaitHandle = new Even开发者_高级运维tWaitHandle(true, EventResetMode.ManualReset, "SOMEGUID");

In Process B :

private static bool IsProcessARunning(string mutexStr)
{
    try
    {
        EventWaitHandle.OpenExisting(mutexStr);
        return true;
    }
    catch (WaitHandleCannotBeOpenedException e)
    {
        return false;
    }
}

But after process A starts once the 'IsProcessARunning' method will always return true even if process A is closed. Any idea what am I doing wrong here ?


replace EventWaitHandle.OpenExisting(mutexStr); with EventWaitHandle.OpenExisting(mutexStr).WaitOne(-1,false); so that you may wait for the event

EDIT:

Change: EventWaitHandle eventWaitHandle = new EventWaitHandle(true, EventResetMode.ManualReset, "SOMEGUID");

to

EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset, "SOMEGUID");

You must call eventWaitHandle.Set() when starting and eventWaitHandle.Reset() when stoping in ProcessA

EDIT2:

Because processA might have crashed you should impement System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(procAName); and check if it is running. If I knew how you will be using this exactly then I could possibly suggest a more appropriate solution. In this case you don't need mutexes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号