在WinRT中。我在后台方法下载,下载进度应在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
}
}
我面临的问题是因为我发生了多次下载操作,所以无法直接执行更新UI的操作。我想知道如何发送绑定到UI的参数DownloadProgress
方法并帮助进行更新操作。
答案 0 :(得分:1)
你可以使用lambdas:
int downloadId = ...;
var progressCallback = new Progress<DownloadOperation>(x => DownloadProgress(x, downloadId));
然后您的进度更新程序可以使用它:
private static void DownloadProgress(DownloadOperation download, int downloadId)
{
... // use downloadId
}