Simon Morgan
Simon Morgan

Reputation: 2248

await WebClient.DownloadFileTaskAsync not working

I'm trying to use WebClient.DownloadFileTaskAsync to download a file so that I can make use of the download progress event handlers. The problem is that even though I'm using await on DownloadFileTaskAsync, it's not actually waiting for the task to finish and exits instantly with a 0 byte file. What am I doing wrong?

internal static class Program
{
    private static void Main()
    {
        Download("http://ovh.net/files/1Gb.dat", "test.out");
    }

    private async static void Download(string url, string filePath)
    {
        using (var webClient = new WebClient())
        {
            IWebProxy webProxy = WebRequest.DefaultWebProxy;
            webProxy.Credentials = CredentialCache.DefaultCredentials;
            webClient.Proxy = webProxy;
            webClient.DownloadProgressChanged += (s, e) => Console.Write($"{e.ProgressPercentage}%");
            webClient.DownloadFileCompleted += (s, e) => Console.WriteLine();
            await webClient.DownloadFileTaskAsync(new Uri(url), filePath).ConfigureAwait(false);
        }
    }
}

Upvotes: 0

Views: 2136

Answers (1)

Paulo Morgado
Paulo Morgado

Reputation: 14836

As others have pointed, The two methods shown are either not asynchronous or not awaitable.

First, you need to make your download method awaitable:

private async static Task DownloadAsync(string url, string filePath)
{
    using (var webClient = new WebClient())
    {
        IWebProxy webProxy = WebRequest.DefaultWebProxy;
        webProxy.Credentials = CredentialCache.DefaultCredentials;
        webClient.Proxy = webProxy;
        webClient.DownloadProgressChanged += (s, e) => Console.Write($"{e.ProgressPercentage}%");
        webClient.DownloadFileCompleted += (s, e) => Console.WriteLine();
        await webClient.DownloadFileTaskAsync(new Uri(url), filePath).ConfigureAwait(false);
    }
}

Then, you either wait on Main:

private static void Main()
{
    DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out").Wait();
}

Or, make it asynchronous, too:

private static async Task Main()
{
    await DownloadAsync("http://ovh.net/files/1Gb.dat", "test.out");
}

Upvotes: 1

Related Questions