重新启动的进程输出不会读取

Restarted Process Output won't Read

本文关键字:读取 输出 进程 重新启动      更新时间:2023-10-16

所以我在C++中制作了一个GUI,每次单击两次按钮时都会调用一个子进程。StandardOutput 是重定向的,不使用 ShellExecute。

我做了一个简单的虚拟过程来测试它,假设 dummy.exe,基本上只是这样做:

void() {
    printf("0");
}

仅此而已。绘制 0 后,进程将自行退出。

单击按钮时启动该过程,该按钮执行以下操作:

private: System::Void bt_getData_Click(System::Object^  sender, System::EventArgs^  e) {
    if (bt_getData->Text == "Get Data") {
        proc->Start();  
        bt_getData->Text = "Stop";
    }
    else if (bt_getData->Text == "Stop") {                  
        bt_getData->Text = "Get Data";
    }
}

然后,它将使用 OutputDataReceived 事件处理程序读取输出。问题是当我再次单击该按钮时,该过程将重新启动,但 GUI 无法读取新的输出。

案例 1:我取消了在输出数据接收事件处理程序中读取的输出,然后重新启动进程,但无法读取下一个重新启动的进程输出。

private: System::Void outputData(System::Object^  sender, System::Diagnostics::DataReceivedEventArgs^  e) {                         
    x0 = xt;
    xt += 1;
    if (xt*x_scale > pb_Graph->Width) {
        x0 = 0;
        xt = 0;
        imgTemp = gcnew Bitmap(pb_Graph->Image, 460, 460);
        gpcGraph->Clear(Color::Transparent);
    }
    y0 = yt;
    yt = Convert::ToInt16(e->Data);
    ret_index++;
    if (ret_index > 2047) ret_index = 0;
    gpcGraph->DrawLine(greenPen,(float)x0*x_scale,pb_Graph->Height - (float)y0/y_scale - y_null,(float)xt*x_scale,pb_Graph->Height - (float)yt/y_scale - y_null);
    pb_Graph->Refresh();
}

重新启动三次后,此错误显示: 系统中发生了类型为"System.InvalidOperationException"的未处理异常.dll

Additional information: An async read operation has already been started on the stream.

情况2:我没有取消输出读取。案例 1 显示了相同的错误,但对我来说仍然是可以理解的。

情况3:重新启动时我没有重做BeginOutputReadLine()。未显示错误,但无法读取重新启动的进程输出。

我的实际目标是使用 1 mS 计时器定期重新启动该过程,因此我首先使用 button 测试了重新启动过程。但似乎无法读取新生成的输出。

任何帮助将不胜感激:)

好的...我已经设法使用不同的方法防止错误,即调用

process->StandardOutput->ReadLine();

这样就不会发生异步流读取。