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

本文关键字:数据 程序 事件处理 等待 | 更新日期: 2023-09-27 18:36:59

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

简单的解决方案是使用同步标志,使用锁来访问它,并放置一个无限循环,该循环在设置标志时中断。有没有更优雅、更安全的方法可以做到这一点?

这是我想要完成的:

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;
            }               
        }

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

你可以像这样使用 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();