异步代码似乎仅在插入断点时才有效



我有以下 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 文件下载到内存流中。我还不知道任何其他方法可以做到这一点。

看起来你基本上是在搞砸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);
} 

最新更新