Async Method skips await

别等时光非礼了梦想. 提交于 2021-02-05 11:52:56

问题


I have the following code:

public async Task<string> GetData(Uri source)
{
    if (client.IsBusy == true) 
        client.CancelAsync ();

    Task<string> tskResult = client.DownloadStringTaskAsync (source);

    string strResult = await tskResult;
    return strResult;
}

When I step through this method starting with Task<string>... the debugger jumps over return strResult; And the value of strResult is null.

Why does this happen? Thanks.

PS: I am calling this method like this:

StringBuilder strBuild = new StringBuilder();

foreach (var image in imageApiUrlLst)
 {
   string imageModelPull = await callMgr.GetData(new Uri(image)); ///WHY GETS STUCK!
   strBuild.AppendLine(imageModelPull);
  }

回答1:


An async method returns as soon as an await statement is reached, if the thing awaited hasn't finished. Once it completes, the method continues execution after that await statement. Try putting a break point on the return statement and it should get hit twice.




回答2:


aysnc marks the method as being asynchronous. await is where execution will continue from WHEN the result comes back from the call.

when you make the request to get tskResult execution cannot complete the following steps as execution has to wait (potentially many clock cycles) so it skips out of this method after first putting down a marker as to where it should return.

When DownloadStringTaskAsync has completed it will come back to this method and ONLY then assign a result. In real time this could be millions of CPU clock cycles after the call was initiated., stepping trough wit the debugger one line at a time you will see the jump and later the call back.

put you break point on return strResult and don't step through. just wait for the call to come back after the client.DownloadStringTaskAsync returns.

Also if during the execution of this method there is an exception then this will be "consumes" by the method so if the code does not break on your return then wrap the whole block in a try catch and also put a breakpoint inside the catch - so you can see what exception you're getting.



来源:https://stackoverflow.com/questions/26458128/async-method-skips-await

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!