2016-11-07 145 views
0

我想用這個方法:我怎樣才能得到返回值時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); 
} 

但我怎麼能參加backgroundWorker1_RunWorkerCompletedSynchronizeFiles返回值。

+1

您應該使用'Task'和'await'來代替。 – SLaks

回答

1

您並不需要backgroundWorker1_DoWork方法,因爲它只是包裝SynchronizeFiles方法調用。你可以改變事件處理方式如下:

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

現在裏面backgroundWorker1_RunWorkerCompleted你可以通過e.Result屬性訪問的結果。

+0

謝謝。 İt的工作好:) –