Mohamad MohamadPoor
Mohamad MohamadPoor

Reputation: 1340

HttpClient.getAsync(URL) Hanged And Don't Reply

I have a strange problem, I need to download a file form this URL in my WPF application. Content of file is a excel file which is compressed. I used code below to download the file but the code stuck in line : await client.getAsync(URL) and I don't know why ! Same code executed well in another system. Can you help me what should I do to get answer well ?

static void Main()
{
    var task =     DownloadFileAsync("http://members.tsetmc.com/tsev2/excel/MarketWatchPlus.aspx?d=0");
    task.Wait();

}

static async Task DownloadFileAsync(string url)
{
    HttpClient client = new HttpClient(new HttpClientHandler { AutomaticDecompression =     DecompressionMethods.GZip });

    HttpResponseMessage response = await client.GetAsync(url);

    // Get the file name from the content-disposition header.
    // This is nasty because of bug in .net:         http://stackoverflow.com/questions/21008499/httpresponsemessage-content-headers-        contentdisposition-is-null
    string fileName = response.Content.Headers.GetValues("Content-Disposition")
        .Select(h => Regex.Match(h, @"(?<=filename=).+$").Value)
        .FirstOrDefault()
        .Replace('/', '_');

    using (FileStream file = File.Create(fileName))
    {
        await response.Content.CopyToAsync(file);
    }
}

If there is another way to download this file and get the name of file or a way to correct this code I will be very thankful.

Upvotes: 0

Views: 1832

Answers (1)

Yuan Shing Kong
Yuan Shing Kong

Reputation: 674

I guess this is because of deadlock.

Configure the awaiter so that it would not continue back to the original context until the task is complete:

HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);

await response.Content.CopyToAsync(file).ConfigureAwait(false);

Upvotes: 3

Related Questions