HttpClient PostAsync 导致等待时死锁

问题描述 投票:0回答:1

我不完全确定发生了什么。 当我使用下面的代码并等待 HttpClient 时,我遇到了死锁并且响应永远不会返回。 如果我将等待放在

await response.Result.Content.ReadAsStringAsync()
上,那么响应将会返回,但是我不确定如何使用
IsSuccessStatusCode

public async Task<string> PostAsyncJSONReadAsString(RESTInformation restInformation, string json)
 {
     var httpClient = GetHttpClient(restInformation);
     var content = new StringContent(json, Encoding.UTF8, "application/json");
     //this line Freezes
     //var response = await httpClient.PostAsync(restInformation.Resource, content);
     var response = httpClient.PostAsync(restInformation.Resource, content);
     var resultContent = await response.Result.Content.ReadAsStringAsync();
     /*if (response.IsSuccessStatusCode)
     {
         return resultContent;
     }*/
     return resultContent;
     /*
     if (response.IsSuccessStatusCode)
     {
         var contents = await response.Content.ReadAsStringAsync();
         return contents;
     }*/
     //else return null;
 }
c# task httpclient
1个回答
0
投票

不要使用

Task.Result
,基本上:

var response = await httpClient.PostAsync(restInformation.Resource, content);
var resultContent = await response.Content.ReadAsStringAsync();
© www.soinside.com 2019 - 2024. All rights reserved.