Channel9Downloader.DataAccess.DownloadManager.DownloadFileAsync C# (CSharp) Method

DownloadFileAsync() private method

Downloads a file asynchronously.
private DownloadFileAsync ( string address, string filename, IDownloadItem downloadItem, CancellationToken token ) : Task
address string The address of the resource to download.
filename string The name of the local file that is to receive the data.
downloadItem IDownloadItem The download item.
token System.Threading.CancellationToken The token for cancelling the operation.
return Task
        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;
        }