【问题标题】:Async code only seems works only when a breakpoint is inserted异步代码似乎仅在插入断点时才有效
【发布时间】:2018-10-17 17:43:34
【问题描述】:

我有以下 C# 代码:

var response = client.GetAsync(uri).Result;
MemoryStream stream = new MemoryStream();
response.Content.CopyToAsync(stream);
System.Console.WriteLine(stream.Length);

当我在第一条语句之前插入断点然后继续程序时,代码运行良好,流中存储了超过 4 MB 的数据。

但是,如果我在没有任何断点的情况下运行程序或在上面显示的第一条语句之后插入断点,则代码会运行但没有数据或只有 4 KB 的数据存储在流中。

谁能解释一下为什么会这样?

编辑: 这是我在我的程序中尝试做的事情。我使用几个 HttpClient.PostAsync 请求来获取 uri 来下载 wav 文件。然后我想将 wav 文件下载到内存流中。我不知道还有其他方法可以做到这一点。

【问题讨论】:

  • 您没有等待response.Content.CopyToAsync(stream); 完成。在这里使用await。尽量避免.Result,因为它是一个阻塞操作
  • 首先,您应该使用 await。所以var response = await client.GetAsync(uri); 以及复制到await response.Content.CopyToAsync(stream);
  • 这是如何异步的?你有 .结果背后的方法。也许我错过了什么?
  • @PeterBons 我在某处读到,如果我们使用.Result,它只会将方法呈现为同步的,即程序会一直等到方法返回,这就是我想要的
  • 但请注意,这可能会导致死锁。你为什么要那样做?

标签: c# asynchronous breakpoints


【解决方案1】:

看来您基本上是在搞乱asyncawait 的流程。

当您使用 await 关键字时,将等待异步调用完成并重新捕获任务。

上述代码并未说明您是否在方法中使用异步签名。让我为您澄清解决方案

可能的解决方案 1:

public async Task XYZFunction()
{
  var response = await client.GetAsync(uri); //we are waiting for the request to be completed
  MemoryStream stream = new MemoryStream();
  await response.Content.CopyToAsync(stream); //The call will wait until the request is completed
  System.Console.WriteLine(stream.Length);
} 

可能的解决方案 2:

public void XYZFunction()
{
  var response = client.GetAsync(uri).Result; //we are running the awaitable task to complete and share the result with us first. It is a blocking call
  MemoryStream stream = new MemoryStream();
  response.Content.CopyToAsync(stream).Result; //same goes here
  System.Console.WriteLine(stream.Length);
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-09
    • 2020-10-18
    • 2021-03-17
    • 2018-07-06
    相关资源
    最近更新 更多