【问题标题】:How to pass objects between threads when running a System.Diagnostics process运行 System.Diagnostics 进程时如何在线程之间传递对象
【发布时间】:2010-11-07 10:47:00
【问题描述】:

我不会提供所有代码,而是我想要做的一个示例。我有这段代码用于从外部进程 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();

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

void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    if (e.Data != null)
    {
        UpdateTextBox(e.Data);
    }
}

它调用以下,它引用一个特定的文本框控件。

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

我想要的是这样的:

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);
    }
}

我可以使用该线程更新不同的文本框,而无需为 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);
    }
}     

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

【问题讨论】:

  • 其实它看起来确实有效,只是我在复制和粘贴时没有将 SetTextBox 更改为 UpdateTextBox。
  • 您能解释一下您遇到的问题吗?
  • 它可以工作,但如果我在那里休息并查看 IDE 中的“Target”,它会说“'Target.Text' 引发了类型为 'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException '"

标签: c# .net winforms multithreading


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    看看这个。

    http://weblogs.asp.net/justin_rogers/pages/126345.aspx

    我以前做过,但我现在没有代码。

    如果我得到它,我会为你发布它,但这篇文章可能有足够的信息让你弄清楚。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多