我正要编辑this answer,但它似乎并不正确。所以我会发布我自己的...
根据Threads for C#页面,其中有很多同步教程,AutoResetEvent
不能用于进程间同步。
然而,一个名为
EventWaitHandle
可用于进程间同步。 在上述页面中,请访问
Creating a Cross-Process EventWaitHandle部分。
您设置此的方式是直接的:
过程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
}
过程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.
现在,关于EventResetMode
。 是否您选择EventResetMode.AutoReset
或EventResetMode.ManualReset
取决于您的应用程序。
在我的情况下,我需要手动重置,因为我有很多进程连接到同一个进程。所以,一旦这个相同的进程完成初始化,所有其他进程应该能够工作。因此,手柄应处于信号状态(不重置)。
对你来说,如果你要为每一次执行初始化过程1点开始过程2自动复位可能会有所帮助。
边注:的
InterprocessProtocol.EventHandleName
是刚刚结束了一个DLL,既
过程1和
过程2参考内部常数。您不需要这样做,但它可以保护您避免误输名称并导致死锁。
AutoResetEvent只能是本地的。但你是对的 - EventWaitHandle正是我所期待的。谢谢! – VitalyB 2010-11-08 12:59:19
为什么不能使用AutoResetEvent和ManualResetEvent进行进程间通信?它们都来自EventWaitHandle – caa 2015-12-30 10:40:17