【发布时间】:2012-10-29 11:09:16
【问题描述】:
我有一个启动子 process 并异步处理其 stdout 的应用程序。问题是异步操作需要一些时间,我希望负责流程执行的方法在所有异步 IO 操作完成后结束。
我有这样的代码:
using System.Diagnostics;
Process process = new Process();
// ...
process.OutputDataReceived += new DataReceivedEventHandler(this.OnRecvStdOut);
process.ErrorDataReceived += new DataReceivedEventHandler(this.OnRecvStdErr);
// ...
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// ...
process.WaitForExit();
现在我正在寻找一种方法来告诉程序等待所有 IO (OnRecvStdOut) 操作完成。
我虽然想使用System.Threading 类之一,但我不确定哪个类最适合这个以及如何做到这一点,最好的方法可能是:
public void OnRecvStdOut(...)
{
something.Increase();
// the stuff that takes so long
something.DecreaseAndSignal();
}
在主函数中:
something.WaitUntilZero();
注意:我希望同时处理 StdErr 和 StdOut。 Something 不能依赖 Wait 和 @ 一样被调用987654333@,因为Increase() 和DecreaseAndSignal() 对会在Wait 发生之前被调用很多次。
想到的第二件事是能够多次发出信号(无需处理信号)并在主函数中使用循环,例如:
while( ioOperations > 0){
something.WaitForSignal(500);
}
编辑:当前工作解决方案:
我想出了这个似乎可行的方法:
using System.Threading;
protected int IOCount = 0;
protected AutoResetEvent _IOSyncEvent = new AutoResetEvent(false);
public void OnRecvStdOut(...)
{
Interlocked.Increase( ref IOCount);
// the stuff that takes so long
Interlocked.Decrease( ref IOCount);
IOSyncEvent.Set();
}
// After process.WaitForExit()
while( IOCount > 0){
// 250 for a case that signal occurs after condition and before wait
IOSyncEvent.WaitOne(250);
}
但我会很感激任何说明如何执行这种“良好实践方式”或我认为实施的可能风险。
【问题讨论】:
-
看起来很像stackoverflow.com/questions/2337166/…。这个问题的答案有帮助吗?
-
实际上,把那条评论划掉。它建议使用反射侵入内部类(基本上,使用未记录的技术)。
标签: c# io synchronization multiple-processes