簡體   English   中英

如何在運行System.Diagnostics進程時在線程之間傳遞對象

[英]How to pass objects between threads when running a System.Diagnostics process

我不會提供所有代碼,而是我想要做的一個例子。 我有這個代碼用於從外部進程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);
    }
}

我可以用來從該線程更新不同的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);
    }
}     

這段代碼現在似乎工作,因為我注意到一個錯字..這可以使用嗎?

您提供的代碼看起來很好,是在線程之間發送此類消息的好方法。

看看這個。

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

我以前做過這個,但我現在沒有代碼。

如果我達到它,我會為你發布,但文章可能有足夠的信息讓你弄明白。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM