HttpClient.GetAsync(…) never returns when using await/async

前端 未结 6 859
[愿得一人]
[愿得一人] 2020-11-22 12:22

Edit: This question looks like it might be the same problem, but has no responses...

Edit: In test case 5 the task appears to be st

6条回答
  •  梦谈多话
    2020-11-22 13:18

    In my case 'await' never finished because of exception while executing the request, e.g. server not responding, etc. Surround it with try..catch to identify what happened, it'll also completes your 'await' gracefully.

    public async Task GetStuff(string id)
    {
        string path = $"/api/v2/stuff/{id}";
        try
        {
            HttpResponseMessage response = await client.GetAsync(path);
            if (response.StatusCode == HttpStatusCode.OK)
            {
                string json = await response.Content.ReadAsStringAsync();
                return JsonUtility.FromJson(json);
            }
            else
            {
                Debug.LogError($"Could not retrieve stuff {id}");
            }
        }
        catch (Exception exception)
        {
            Debug.LogError($"Exception when retrieving stuff {exception}");
        }
        return null;
    }
    

提交回复
热议问题