【发布时间】:2013-10-30 19:14:12
【问题描述】:
我有一些文件需要在应用启动(首次运行)时下载。 我在 Windows 8 中使用后台下载器。 我就是这样使用它的:
BackgroundDownloader downloader = new BackgroundDownloader();
List<DownloadOperation> operations = new List<DownloadOperation>();
foreach (FileInfo info in infoFiles)
{
Windows.Storage.ApplicationData.Current.LocalFolder;
foreach (string folder in info.Folders)
{
currentFolder = await currentFolder.CreateFolderAsync(folder, CreationCollisionOption.OpenIfExists);
}
//folder hierarchy created, save the file
StorageFile file = await currentFolder.CreateFileAsync(info.FileName, CreationCollisionOption.ReplaceExisting);
DownloadOperation op = downloader.CreateDownload(new Uri(info.Url), file);
activeDownloads.Add(op);
operations.Add(op);
}
foreach (DownloadOperation download in operations)
{
//start downloads
await HandleDownloadAsync(download, true);
}
当我尝试使用BackgroundDownloader.GetCurrentDownloadsAsync(); 时,我只发现了一个后台下载。所以我删除了上面的 await 操作符,让它们异步启动。
但是我需要知道所有文件何时完成,以便设置进度条。
我需要一种下载多个文件的方法,在 BackgroundDownloader.GetCurrentDownloadsAsync(); 中发现所有文件并知道所有下载何时完成。
private async Task HandleDownloadAsync(DownloadOperation download, bool start)
{
try
{
Debug.WriteLine("Running: " + download.Guid, NotifyType.StatusMessage);
// Store the download so we can pause/resume.
activeDownloads.Add(download);
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
if (start)
{
// Start the download and attach a progress handler.
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
// The download was already running when the application started, re-attach the progress handler.
await download.AttachAsync().AsTask(cts.Token, progressCallback);
}
ResponseInformation response = download.GetResponseInformation();
Debug.WriteLine(String.Format("Completed: {0}, Status Code: {1}", download.Guid, response.StatusCode),
NotifyType.StatusMessage);
}
catch (TaskCanceledException)
{
Debug.WriteLine("Canceled: " + download.Guid, NotifyType.StatusMessage);
}
catch (Exception ex)
{
if (!IsExceptionHandled("Execution error", ex, download))
{
throw;
}
}
finally
{
activeDownloads.Remove(download);
}
}
【问题讨论】:
标签: c# windows-store-apps background-transfer