Consider the following scenario: I'm running my application which, during its execution, has to run another process and only after that 2nd process finishes inner specific initialization, can my first process continue. E.g:
...
// Process1 code does various initializations here
Process.Start("Process2.exe");
// Wait until Process2 finishes its initialization and only then continue (Process2 doesn't exit)
...
I see several options:
I'd be happy to hear your opinion for this case.
Thanks!
I was just going to edit this answer, but it doesn't seem correct. So I'll post my own...
According to the Threads for C# page, which has a lot of synchronization tutorials, AutoResetEvent
cannot be used for interprocess synchronization.
EventWaitHandle
can be used for interprocess synchronization.
In the above page, visit the Creating a Cross-Process EventWaitHandle section.
The way you set this up is straight-forward:
EventWaitHandle
in process 1, before starting process 2.EventWaitHandle.WaitOne
to block the current thread.EventWaitHandle
in process 2 and invoke EventWaitHandle.Set
to release the waiting thread.Process 1
EventWaitHandle handle = new EventWaitHandle(
false, /* Create handle in unsignaled state */
EventResetMode.ManualReset, /* Ignored. This instance doesn't reset. */
InterprocessProtocol.EventHandleName /* String defined in a shared assembly. */
);
ProcessStartInfo startInfo = new ProcessStartInfo("Process2.exe");
using (Process proc = Process.Start(startInfo))
{
//Wait for process 2 to initialize.
handle.WaitOne();
//TODO
}
Process 2
//Do some lengthy initialization work...
EventWaitHandle handle = new EventWaitHandle(
false, /* Parameter ignored since handle already exists.*/
EventResetMode.ManualReset, /* Explained below. */
InterprocessProtocol.EventHandleName /* String defined in a shared assembly. */
);
handle.Set(); //Release the thread waiting on the handle.
Now, regarding the EventResetMode
.
Whether you choose EventResetMode.AutoReset
or EventResetMode.ManualReset
depends on your application.
In my case, I needed a manual reset because I have have many processes connecting to the same process. So, once this same process is done being initialized, all of the other processes should be able to do work. Thus, the handle should be left in a signaled state (no reset).
For you, an automatic reset might be helpful if you have to perform initialization for every time process 1 starts process 2.
InterprocessProtocol.EventHandleName
is just a constant wrapped up inside a DLL that both process 1 and process 2 reference. You do not need to do this, but it protects you from mis-typing the name and causing a deadlock.
i would consider **AutoResetEvent **. they can be used for interprocess communcation and they are relativley fast. see the following link: Threads for c#
read the Creating a Cross-Process EventWaitHandle section...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With