背景
我正在为 Node.js 应用程序编写一个 C# 包装器。在此包装器中,我通过 Process.RedirectStandardOutput 不断读取标准输出。该事件绑定(bind)到 ProcessManager
类实例中的函数 onOutputDataReceived
。在同一实例中,还有一个自定义事件系统的实例。
[进程管理器
]
EventSystem eventSystem;
private void Start()
{
[...]
process.OutputDataReceived += onOutputDataReceived;
[...]
}
private void onOutputDataReceived(object sender, DataReceivedEventArgs e)
{
[...]
eventSystem.call(eventName, args);
}
[事件系统
]
List<EventHandler> eventList;
public Boolean call(String eventName, dynamic args)
{
[...]
foreach (EventHandler handler in eventList)
{
handler(args);
}
[...]
}
问题发生在调用事件时。这是使用我的包装器的 winforms 应用程序的示例。
Wrapper.ProcessManager procMan;
procMan.eventSystem.on(eventName, (a) =>
{
button1.Text = someValue;
});
运行时,应用程序崩溃并显示消息
Cross-thread operation not valid: Control 'button1' accessed from a thread other than the thread it was created on
据我了解,我的问题是这样的:
onOutputDataReceived
正在其自己的线程中异步执行。由于同一个线程仅用于处理输出,因此继续调用事件,我无意中对我的包装器进行了多线程处理,使实现它的任何人的生活变得更加困难。
基本上,
一旦收到新的输出数据,我需要在维护 ProcessManager 实例其余部分的同一线程中运行 eventSystem.call()
行尽可能。关于如何最好地实现这一目标有什么想法吗?
解决方案我想到的是这样的
[进程管理器
]
Queue<string> waiting = new Queue<string();
EventSystem eventSystem;
private void onOutputDataReceived(object sender, DataReceivedEventArgs e)
{
[...]
waiting.Enqueue(eventName);
}
private void WhenReady()
{
while(waiting.Count > 0)
eventSystem.call(waiting.Dequeue());
}
据我所知,这将涉及每 x 毫秒进行某种轮询,这感觉不是一个干净的解决方案。另外,在我看来,这样的解决方案对于没有收到消息的情况来说太昂贵了,而对于收到消息的情况来说又太慢了。
最佳答案
执行nodejs进程并读取其输出的代码不需要了解事件订阅者的线程要求。让订阅者满足自己的需求:
(a) =>
{
Invoke(new Action(() => button1.Text = someValue)); //marshal to UI thread
}
您的暂定解决方案将不起作用,因为它会阻塞 UI 线程。
此外,waiting
正在以不同步的方式使用...这是一个不相关的错误。
关于c# - 重新同步 Process.RedirectStandardOutput,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36670456/