等待来自事件处理程序的某些数据

时间:2016-03-01 19:21:08

标签: c# event-handling redirectstandardoutput

我正在调用外部可执行文件并从其标准输出流异步读取。我需要等待从流中传递一些数据。

简单的解决方案是使用同步标志,使用锁来访问它,并设置一个无限循环,在设置标志时突破。 这样做有更优雅,更安全的方式吗?

这是我想要完成的事情:

bool sync = false;
Object thisLock = new Object();

MyExec.StartInfo.RedirectStandardOutput = true;
MyExec.StartInfo.UseShellExecute = false;
MyExec.OutputDataReceived += new DataReceivedEventHandler(
            (s, e) =>
            {
                if (String.IsNullOrWhiteSpace(e.Data) || e.Data.Contains('X')
                    lock (thisLock)
                    {
                        sync = true;
                    }
            });
...
while (true)
        {
            Thread.Sleep(1000);
            lock (thisLock)
            {
                if (sync) break;
            }               
        }

1 个答案:

答案 0 :(得分:1)

您可以像这样使用ManualResetEvent类:

ManualResetEvent mre = new ManualResetEvent(false);

MyExec.OutputDataReceived += new DataReceivedEventHandler(
        (s, e) =>
        {
            if (String.IsNullOrWhiteSpace(e.Data) || e.Data.Contains('X'))
                mre.Set();
        });

...
//On the other thread

//This will wait until the ManualResetEvent is signaled via mre.Set();
mre.WaitOne();