简体   繁体   中英

Code stuck when the response of an async request is 404 status code

My code is getting stuck on GetAsync().Result . The GetAsync() method is the following:

I am calling an API endpoint asynchronously like this:

public async Task<List<Account>> GetAsync(string feature, string licenseType, string token)
{
   // Find accounts that have a license for the user
   var accounts = await _licenseMgr.GetAccountsAsync(
      feature,
      licenseType,
      token);

   return accounts;
}

After the awaited method is ran, the code simply gets stuck. When checking with Fiddler, it appears that the response header is HTTP/1.1 404 Not Found .

Why is the code getting stuck there instead of, at least, returning null or something?

Most likely the problem is that the GetAsync wants to continue execution after GetAccountsAsync finished on the thread, which is blocked with the Result call. And at the same time the blocked thread wants to get result of GetAsync to unlock. Thus, we have classical deadlock here.

The correct solution here will be to avoid using Result/GetReult/Wait() and other blocking things in the async code. The best way to solve the hang will be to replace GetAsync().Result with await GetAsync() .

If such a replacement is hard to implement, you can try to forcefully put the task on the thread pool (and thus drop a current synchronization context)

var result = Task.Run(async () => await GetAsync()).Result;

(this one will or will not work depending on your environment)

The other way is to completely switch to the synchronous API everywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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