那么,问题是为什么在 using 块中使用 HttpClient 是错误的,但在 WebApi 上下文中呢?
我一直在阅读这篇文章“不要阻止异步代码”。其中我们有以下示例:
public static async Task<JObject> GetJsonAsync(Uri uri)
{
// (real-world code shouldn't use HttpClient in a using block; this is just example code)
using (var client = new HttpClient())
{
var jsonString = await client.GetStringAsync(uri);
return JObject.Parse(jsonString);
}
}
// My "top-level" method.
public class MyController : ApiController
{
public string Get()
{
var jsonTask = GetJsonAsync(...);
return jsonTask.Result.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
评论// (real-world code shouldn't use HttpClient in a using …