简体   繁体   中英

How can I get the return value when backgroundworker is complete

I want to use this method:

public static bool SynchronizeFiles(string source, string destination)

in BackgroundWorker . I define BackgroundWorker and add it in workerList . Than do this work one by one.

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

But how can I take return value of SynchronizeFiles in backgroundWorker1_RunWorkerCompleted .

You don't really need the backgroundWorker1_DoWork method since it's only wrapping the SynchronizeFiles method call. You can change the event handler the following way:

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

Now inside backgroundWorker1_RunWorkerCompleted you can access the result via the e.Result property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM