如何在backgroundworker完成后获取返回值

时间:2016-11-07 19:22:41

标签: c# .net backgroundworker

我想使用这种方法:

public static bool SynchronizeFiles(string source, string destination)
BackgroundWorker中的

。我定义BackgroundWorker并将其添加到workerList中。而不是逐一做这项工作。

private void CopyIfIsReady(Save save)
{
    if (save.isDriveReady && save.isFileChanged && save.isPeriodCompleted)
    {
        BackgroundWorker BW = new BackgroundWorker();
        BW.DoWork += (obj, e) => backgroundWorker1_DoWork(save);
        BW.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
        workerList.Add(BW);
        BW_timer.Start(500);
    }
}

private void BWTimerCallBack(object state)
{
    if (workerList.Count >= 0)
    {
        if(!workerList[0].IsBusy)
        {
            workerList[0].RunWorkerAsync();
        }
    }
    else
    {
        BW_timer.Stop();
    }
}

private void backgroundWorker1_DoWork(Save save)
{
    SynchronizeFiles(save.sourceFolder, save.destFolder);
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     workerList.RemoveAt(0);
}

但是如何在SynchronizeFiles中获取backgroundWorker1_RunWorkerCompleted的返回值。

1 个答案:

答案 0 :(得分:1)

您实际上并不需要backgroundWorker1_DoWork方法,因为它只包含SynchronizeFiles方法调用。您可以通过以下方式更改事件处理程序:

BW.DoWork += (obj, e) => { e.Result = SynchronizeFiles(save.sourceFolder, save.destFolder); }

现在在backgroundWorker1_RunWorkerCompleted内,您可以通过e.Result属性访问结果。