c# - 重新同步 Process.RedirectStandardOutput

标签 c# multithreading process stdout

背景

我正在为 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/

相关文章:

asp.net-mvc - ASP.NET MVC 重复任务

java Process,getInputStream,仅读取最新行

ruby - 通过 ruby​​ 进程共享变量

c# - 控制 USB 端口的电源?

c# - 如何将 xml 节点加载到 html 文本框中

java - 两个线程调用相同的 keyEvents 方法

vba - VBA CreateProcess将StdIn和StdOut重定向到Socket吗?

c# - XML 异常 : Invalid Character(s)

c# - 我应该在我的 LINQ 查询中使用两个 "where"子句还是 "&&"?

c++ - 通知另一个线程数据可用的最快方法是什么?除了纺纱还有其他选择吗?