在线程之间同步字节[2400000]

时间:2015-04-15 12:13:34

标签: c# multithreading backgroundworker

我想在后台工作程序中创建一个大字节数组。完成工作后,后台工作人员应将数据提供给主线程。

我该怎么做?

1 个答案:

答案 0 :(得分:6)

在后台工作程序DoWork event handler中,使用Result参数的DoWorkEventArgs成员返回字节数组。

然后,在后台工作人员RunWorkerCompleted event handler中,阅读Result参数的RunWorkerCompletedEventArgs成员。

来自链接的MSDN文档的

DoWork 示例:

// This event handler is where the actual, 
// potentially time-consuming work is done. 
private void backgroundWorker1_DoWork(object sender, 
    DoWorkEventArgs e)
{   
    // Get the BackgroundWorker that raised this event.
    BackgroundWorker worker = sender as BackgroundWorker;

    // Assign the result of the computation 
    // to the Result property of the DoWorkEventArgs 
    // object. This is will be available to the  
    // RunWorkerCompleted eventhandler.
    e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
来自链接的MSDN文档的

RunWorkerCompleted 示例:

// This event handler deals with the results of the 
// background operation. 
private void backgroundWorker1_RunWorkerCompleted(
    object sender, RunWorkerCompletedEventArgs e)
{
    // First, handle the case where an exception was thrown. 
    if (e.Error != null)
    {
        MessageBox.Show(e.Error.Message);
    }
    else if (e.Cancelled)
    {
        // Next, handle the case where the user canceled  
        // the operation. 
        // Note that due to a race condition in  
        // the DoWork event handler, the Cancelled 
        // flag may not have been set, even though 
        // CancelAsync was called.
        resultLabel.Text = "Canceled";
    }
    else
    {
        // Finally, handle the case where the operation  
        // succeeded.
        resultLabel.Text = e.Result.ToString();
    }

    // Enable the UpDown control. 
    this.numericUpDown1.Enabled = true;

    // Enable the Start button.
    startAsyncButton.Enabled = true;

    // Disable the Cancel button.
    cancelAsyncButton.Enabled = false;
}