HttpClient.getAsync(URL)被搁置并且没有回复

时间:2014-07-16 12:50:07

标签: c# wpf download httpclient

我有一个奇怪的问题,我需要在我的WPF应用程序中下载this URL文件。文件内容是压缩的excel文件。我使用下面的代码下载文件,但代码卡在一行:await client.getAsync(URL),我不知道为什么!相同的代码在另一个系统中执行良好你能帮我解决一下我的答案吗?

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);
    }
}

如果有另一种方法可以下载此文件并获取文件名或更正此代码的方法,我将非常感谢。

1 个答案:

答案 0 :(得分:3)

我想这是因为死锁。

配置awaiter,以便在任务完成之前它不会继续回到原始上下文:

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

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