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

时间:2013-09-14 02:56:32

标签: c++ visual-c++ process

所以我在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 EventHandler读取输出。 问题是当我再次单击该按钮时,该过程将重新启动,但GUI无法读取新的输出。

情况1:我取消了OutputDataReceived EventHandler中的输出读取,然后重新启动进程,但无法读取下一个重新启动的进程输出。

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.dll

中发生了未处理的“System.InvalidOperationException”类型异常
Additional information: An async read operation has already been started on the stream.

案例2:我没有取消输出读取。与案例1相同的错误显示,但我仍然可以理解。

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

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

任何帮助将不胜感激:)

1 个答案:

答案 0 :(得分:0)

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

process->StandardOutput->ReadLine();

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