我有如下代码
public async Task<object> GetMethod()
{
object result = null;
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, "www.fo");
HttpResponseMessage responseMessage = await client.SendAsync(requestMessage);
if (ok)
{
dynamic data = JObject.Parse(responseMessage.Content.ReadAsStringAsync().Result);
result = data.result.paameter1.tables.paamete2.row.ToString();
}
return result
}
观察是client.SendAsync(requestMessage);需要花费太多时间,考虑到性能,还有其他更好的方法吗?
这样会更好
private async Task<T> Post<T>(string url, object obj) where T : class
{
var jsonString = _jsonHelper.SerializeObject(obj);
var stringContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
var response = await _httpClient.PostAsync(url, stringContent).ConfigureAwait(false);
var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
if(!response.IsSuccessStatusCode)
{
//throw
}
var responseObj = _jsonHelper.DeserializeObject<T>(responseString);
return responseObj;
}
用法
public Task<SomeTypedObject> DoSomething(int someValue)
{
var url = "someUrl";
var requestObject= new ClassForRequest { proptery1 = someValue};
return Post<SomeTypedObject>(url, requestObject);
}
您的主要问题是我没有在ReadAsStringAsync上使用await,您的问题是线程阻塞。但是我非常怀疑这不是您想要“性能”的原因。
PS,显示您的HttpClient生命周期,最有可能出现此问题。
对您来说,是1次请求要花多长时间或其每分钟x次执行此操作的能力。