private Task<object> DownloadFileAsync(
string address,
string filename,
IDownloadItem downloadItem,
CancellationToken token)
{
var tcs = new TaskCompletionSource<object>();
var webClient = _composer.GetExportedValue<IWebDownloader>();
token.Register(webClient.CancelAsync);
webClient.DownloadFileCompleted += (obj, args) =>
{
if (args.Cancelled)
{
tcs.TrySetCanceled();
downloadItem.DownloadState = DownloadState.Stopped;
return;
}
if (args.Error != null)
{
tcs.TrySetException(args.Error);
downloadItem.DownloadState = DownloadState.Error;
return;
}
tcs.TrySetResult(null);
downloadItem.DownloadState = DownloadState.Finished;
};
webClient.DownloadProgressChanged += (obj, args) =>
{
downloadItem.ProgressPercentage = args.ProgressPercentage;
downloadItem.BytesReceived = args.BytesReceived;
downloadItem.TotalBytesToReceive = args.TotalBytesToReceive;
};
try
{
webClient.DownloadFileAsync(new Uri(address), filename);
downloadItem.DownloadState = DownloadState.Downloading;
}
catch (UriFormatException ex)
{
tcs.TrySetException(ex);
}
return tcs.Task;
}