Skip to main content

Downloading a file : TaskCompleteSource approach






string dowloadFilePath = @"D:\InstanceType.json";
            Task<bool> task = DownloadPriceListCsvFromAWS("https://pricing.us-east-1.amazonaws.com/offers/v1.0/aws/AmazonEC2/current/us-gov-east-1/index.json", dowloadFilePath);
            task.Wait(60000);
            if (task.IsCompleted)
            {
                Console.WriteLine("File download compalete {0}", task.Result);
            }
            else
            {
                Console.WriteLine("Download does not seem to be completed within the specified time");
                WebClient webClient = (WebClient)task.AsyncState;
                webClient.CancelAsync();
                bool bRet = task.Result;
                if (File.Exists(dowloadFilePath))
                {
                    Console.WriteLine("Partially downloaded file exist. Cleaning it up");
                    File.Delete(dowloadFilePath);
                }
            }

 private static Task<bool> DownloadPriceListCsvFromAWS(string url, string downloadfilepath)
        {
            System.Net.WebClient webClinet = new System.Net.WebClient();
            TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(webClinet);
            webClinet.DownloadFileCompleted += (SendOrPostCallback, eventArgs) =>
            {
                if (eventArgs.Cancelled || eventArgs.Error != null)
                {
                    Console.WriteLine("Download operation either cancelled or an error occured");
                    tcs.SetResult(false);
                }
                else {
                    Console.WriteLine("Completed downloading the file");
                    tcs.SetResult(true);
                }
            };
            webClinet.DownloadFileAsync(new Uri(url), downloadfilepath);
            return tcs.Task;
        }

Comments