如何在运行System.Diagnostics进程时在线程之间传递对象

dav*_*ave 5 .net c# multithreading winforms

我不会提供所有代码,而是我想要做的一个例子.我有这个代码用于从外部进程stderr更新GUI元素.

我设置了这样的流程:

ProcessStartInfo info = new ProcessStartInfo(command, arguments);

// Redirect the standard output of the process. 
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.CreateNoWindow = true;

// Set UseShellExecute to false for redirection
info.UseShellExecute = false;

proc = new Process();
proc.StartInfo = info;
proc.EnableRaisingEvents = true;

// Set our event handler to asynchronously read the sort output.
proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
proc.Exited += new EventHandler(proc_Exited);

proc.Start();

// Start the asynchronous read of the sort output stream. Note this line!
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
Run Code Online (Sandbox Code Playgroud)

然后我有一个事件处理程序

void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
    {
        UpdateTextBox(e.Data);
    }
}
Run Code Online (Sandbox Code Playgroud)

其中调用以下内容,引用特定的文本框控件.

private void UpdateTextBox(string Text)
{
    if (this.InvokeRequired)
        this.Invoke(new Action<string>(this.SetTextBox), Text);
    else
    {
        textBox1.AppendText(Text);
        textBox1.AppendText(Environment.NewLine);
    }
}
Run Code Online (Sandbox Code Playgroud)

我想要的是这样的:

private void UpdateTextBox(string Text, TextBox Target)
{
    if (this.InvokeRequired)
        this.Invoke(new Action<string, TextBox>(this.SetTextBox), Text, Target);
    else
    {
        Target.AppendText(Text);
        Target.AppendText(Environment.NewLine);
    }
}
Run Code Online (Sandbox Code Playgroud)

我可以用来从该线程更新不同的Textbox,而不必为GUI中的每个控件创建一个单独的函数.

这可能吗?(显然上面的代码不能正常工作)

谢谢.

更新:

private void UpdateTextBox(string Text, TextBox Target)
{
    if (this.InvokeRequired)
        this.Invoke(new Action<string, TextBox>(this.**UpdateTextBox**), Text, Target);
    else
    {
        Target.AppendText(Text);
        Target.AppendText(Environment.NewLine);
    }
}     
Run Code Online (Sandbox Code Playgroud)

这段代码现在似乎工作,因为我注意到一个错字..这可以使用吗?

Pie*_*kel 1

您提供的代码看起来不错,并且是在线程之间发送此类消息的好方法。