2015-10-14 61 views
0

在WinRT中。我在後臺方法下載並下載進度應在UI部分更新。如何在使用BackgroundDownloader並行下載時更新UI?

我的代碼是

   public async static Task DownloadSingleFile(string name, SoundClass sc) 
      { 
        var dl = new BackgroundDownloader(); 
        dl.CostPolicy = BackgroundTransferCostPolicy.Always; 
        file = await localSoundsFolder.CreateFileAsync(name, CreationCollisionOption.ReplaceExisting); 

        var d = dl.CreateDownload(new Uri(uriToDownloadFrom), file); 
        d.Priority = BackgroundTransferPriority.Default; 

        var progressCallback = new Progress<DownloadOperation>(DownloadProgress); 
        try 
        { 
         await d.StartAsync().AsTask(cancellationToken.Token, progressCallback); 
         CancellationTokenSource token = Utility.cancellationList[sc]; 
         if (token != null) 
         { 
          token.Cancel(); 
          Utility.cancellationList.Remove(sc); 
          Debug.WriteLine("The sc has been removed from the download list"); 
         } 
        } 
        catch 
        { 
         return; 
        } 
       } 

以及下載方法看起來像這樣

 private static void DownloadProgress(DownloadOperation download) 
     { 
      Debug.WriteLine("Callback"); 
      var value = download.Progress.BytesReceived * 100/download.Progress.TotalBytesToReceive; 
      Debug.WriteLine("The bytesReceived is {0} and total bytes is {1}", download.Progress.BytesReceived.ToString(), download.Progress.TotalBytesToReceive.ToString()); 
      new System.Threading.ManualResetEvent(false).WaitOne(10); 
      //Update the UI here 
      if (download.Progress.Status == BackgroundTransferStatus.Completed || value >= 100) 
      { 
       //Perform opertaion 
      } 
     } 

我現在面臨的問題是,因爲我有多個下載操作發生的事情,我不能直接執行該操作更新用戶界面。我想知道如何發送參數DownloadProgress方法,該方法綁定到UI並幫助更新操作。

+0

能否請你告訴或共享一些資源,這是多個文件的執行有幫助與實時進度和取消選項下載 –

回答

1

你可以使用lambda表達式這個:

int downloadId = ...; 
var progressCallback = new Progress<DownloadOperation>(x => DownloadProgress(x, downloadId)); 

那麼你的進步更新可以使用它:

private static void DownloadProgress(DownloadOperation download, int downloadId) 
{ 
    ... // use downloadId 
} 
+0

謝謝!正是我在找什麼! – AbsoluteSith

相關問題