Resharper建议使用单行await using语句来改进使用带有await关键字的using语句。例如,以下代码片段:
这两段代码片段是否相似?这里实际上改进了什么?我不理解C#中使用语句的这个特性。
private async Task<string> ReadResponseAsync(HttpContext context)
{
var originalBody = context.Response.Body;
try
{
using (var responseStream = new MemoryStream())
{
context.Response.Body = responseStream;
await _next(context).ConfigureAwait(false);
var response = context.Response;
response.Body.Seek(0, SeekOrigin.Begin);
using (var responseReader = new StreamReader(response.Body))
{
var responseContent = await responseReader
.ReadToEndAsync()
.ConfigureAwait(false);
response.Body.Seek(0, SeekOrigin.Begin);
await responseStream.CopyToAsync(originalBody)
.ConfigureAwait(false);
return responseContent;
}
}
}
finally
{
context.Response.Body = originalBody;
}
}
在应用连续的 Resharper 建议后,代码变成了以下内容:
private async Task<string> ReadResponseAsync(HttpContext context)
{
var originalBody = context.Response.Body;
try
{
await using var responseStream = new MemoryStream();
context.Response.Body = responseStream;
await _next(context).ConfigureAwait(false);
var response = context.Response;
response.Body.Seek(0, SeekOrigin.Begin);
using var responseReader = new StreamReader(response.Body);
var responseContent = await responseReader
.ReadToEndAsync()
.ConfigureAwait(false);
response.Body.Seek(0, SeekOrigin.Begin);
await responseStream.CopyToAsync(originalBody)
.ConfigureAwait(false);
return responseContent;
}
finally
{
context.Response.Body = originalBody;
}
}
这两段代码片段是否相似?这里实际上改进了什么?我不理解C#中使用语句的这个特性。