简体   繁体   English

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

[英]Async code only seems works only when a breakpoint is inserted

I have the following C# code: 我有以下C#代码:

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

When I insert a breakpoint before the first statement and then continue the program, the code works fine and over 4 MB of data gets stored in the stream. 当我在第一条语句之前插入断点然后继续执行程序时,代码可以正常工作,并且流中存储了4 MB以上的数据。

But if I run the program without any breakpoints or inserting the breakpoint after the after the first statement shown above, the code runs but no data or only 4 KB of data gets stored in the stream. 但是,如果我在没有任何断点的情况下运行程序,或者在上面显示的第一条语句之后插入断点,则代码将运行,但是流中没有数据或仅存储4 KB数据。

Can someone please explain why this is happening? 有人可以解释为什么会这样吗?

Edit: Here is what I am trying to do in my program. 编辑:这是我想在程序中执行的操作。 I use couple of HttpClient.PostAsync requests to get a uri to download a wav file. 我使用几个HttpClient.PostAsync请求来获取一个uri以下载wav文件。 Then I want to download the wav file into a memory stream. 然后,我想将wav文件下载到内存流中。 I don't know of any other ways to do this yet. 我还不知道有其他方法可以做到这一点。

It seems like you are basically messing the flow of async and await . 看来您基本上已经弄乱了asyncawait的流程。

The async call will be waited to complete and recapture the task when you use await keyword. 当您使用await关键字时,将等待异步调用完成并重新捕获任务。

The mentioned code does not clarify whether you are using the async signature in your method or not. 上面提到的代码并未阐明您是否在方法中使用了异步签名。 Let me clarify the solution for you 让我为您澄清解决方案

Possible solution 1: 可能的解决方案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);
} 

Possible solution 2: 可能的解决方案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);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM