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

0 c# multithreading backgroundworker

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

我怎样才能做到这一点?

Uwe*_*eim 6

在后台工作DoWork程序事件处理程序中,使用参数的Result成员DoWorkEventArgs返回字节数组.

然后,在后台工作RunWorkerCompleted程序事件处理程序中,读取参数的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);
}
Run Code Online (Sandbox Code Playgroud)

来自链接的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;
}
Run Code Online (Sandbox Code Playgroud)