【问题标题】:HttpClient.getAsync(URL) Hanged And Don't ReplyHttpClient.getAsync(URL) 挂了,不回复
【发布时间】:2014-07-16 12:50:06
【问题描述】:

我有一个奇怪的问题,我需要在我的 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);
    }
}

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

【问题讨论】:

    标签: c# wpf download httpclient


    【解决方案1】:

    我猜这是因为死锁。

    配置等待者,使其在任务完成之前不会继续返回原始上下文:

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

    【讨论】:

    • 非常感谢,现在我被困在另一个地方,在这一行:使用 (FileStream file = File.Create(fileName)) !!!它出什么问题了 ?我可以在没有 await 和 async 的情况下使用这些方法吗?
    • 如果您得到的错误仍然相同,我建议您尝试将上述 2 次异步调用拆分为 2 种不同的方法,因为第 2 次调用取决于第 1 次调用的输出。然后你可以在你的调用者方法中协调它。
    猜你喜欢
    • 2015-07-26
    • 2014-03-26
    • 2022-01-12
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2021-04-11
    相关资源
    最近更新 更多