【发布时间】:2020-01-07 07:31:46
【问题描述】:
我的公司有一个他们编写的 Nuget 包,可以轻松地为您完成各种常见任务。其中之一是发出 HTTP 请求。通常我总是使我的 HTTP 请求异步,但是在这个 Nuget 包中是以下代码:
protected T GetRequest<T>(string requestUri)
{
// Call the async method within a task to run it synchronously
return Task.Run(() => GetRequestAsync<T>(requestUri)).Result;
}
调用这个函数:
protected async Task<T> GetRequestAsync<T>(string requestUri)
{
// Set up the uri and the client
string uri = ParseUri(requestUri);
var client = ConfigureClient();
// Call the web api
var response = await client.GetAsync(uri);
// Process the response
return await ProcessResponse<T>(response);
}
我的问题是,这段代码真的是通过将 GetRequestAsync(requestUri) 包装在 Task.Run 中并在返回的任务上调用 .Result 来实现同步运行的吗?这似乎是一个等待发生的死锁,我们在应用程序的某些区域看到了问题,这些问题在以较高负载运行时使用此功能。
【问题讨论】:
-
在
Task上调用.Result将导致它同步等待直到完成。 -
每个人都在说不要使用那个库,或者至少不要使用那个方法。另一个应该按照礼仪使用
ConfigureAwait(false)。发出 HTTP 请求并不难,如果必须正确,请自行完成。
标签: c# asp.net async-await