C#Async,Await和ConfigureAwait的关系
以下是ConfigureAwait(false)的示例:
public async Task<int> ExecuteAsync(UpdateCarCommand request, CancellationToken token = default)
{
using (var context = _contextFactory.Create())
{
var entity = context.Cars.FirstOrDefault(a => a.Id == request.Id);
// Mapping logic
return await context.SaveChangesAsync(token).CongifureAwait(false);
}
}
[ ]
public IActionResult Put([FromBody]UpdateCommand command) =>
_responseMediator.ExecuteAsync(command).ConfigureAwait(false).GetAwaiter().GetResult();
以下代码为例:
private HttpClient _client = new HttpClient();
async Task<List<string>> GetBothAsync(string url1, string url2)
{
var result = new List<string>();
var task1 = GetOneAsync(result, url1);
var task2 = GetOneAsync(result, url2);
await Task.WhenAll(task1, task2);
return result;
}
async Task GetOneAsync(List<string> result, string url)
{
var data = await _client.GetStringAsync(url);
result.Add(data);
}
评论