我在使用Background Downloader下载多个文件时遇到问题。我没有将#34;对象设置为对象的实例"我HandleDownloadAsync
方法中的错误。这是我的代码。
private async Task StartDownload(List<DownloadData> data)
{
foreach (DownloadData song in data)
{
Uri source = new Uri(song.downloadUrl);
// Create folder stucture
StorageFolder artistFolder = await KnownFolders.MusicLibrary.CreateFolderAsync(song.artistName, CreationCollisionOption.OpenIfExists);
StorageFolder releaseFolder = await artistFolder.CreateFolderAsync(song.releaseName, CreationCollisionOption.OpenIfExists);
// Create file
StorageFile destinationFile;
try
{
destinationFile = await releaseFolder.CreateFileAsync(song.fileName, CreationCollisionOption.GenerateUniqueName);
}
catch
{
throw;
}
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(source, destinationFile);
List<DownloadOperation> requestOperations = new List<DownloadOperation>();
requestOperations.Add(download);
await HandleDownloadAsync(download, true);
}
}
和方法
private async Task HandleDownloadAsync(DownloadOperation download, bool start)
{
try
{
// Store the download for pause/resume
activeDownloads.Add(download); // Error occurs here
Progress<DownloadOperation> progressCallback = new Progress<DownloadOperation>(DownloadProgress);
if (start)
{
await download.StartAsync().AsTask(cts.Token, progressCallback);
}
else
{
await download.AttachAsync().AsTask(cts.Token, progressCallback);
}
}
catch
{
throw;
}
finally
{
activeDownloads.Remove(download);
}
}
尝试将下载添加到activeDownloads
时会引发错误。大部分代码来自This MSDN示例,但我添加了foreach循环来下载多个项目。
答案 0 :(得分:0)
好像您可能忘记在StartDownload方法中初始化活动的下载列表,例如:
activeDownloads = new List<DownloadOperation>();