我正在嘗試直接Response.Body在 ASP.NET Core 6 控制器方法中寫入,因為在某些情況下它的性能更高。
為什么在下面的代碼中有不同await using的using行為?
[Route("api/[Controller]/[Action]")]
public class TestController : ControllerBase
{
[HttpGet]
[Produces("text/plain")]
public async Task GetPlainText()
{
// No `using`: it works
// Add `using` to the following line and the response will be empty
// Add `await using` to the following line and it will work
var sw = new StreamWriter(Response.Body, leaveOpen: true);
await sw.WriteAsync("Some normal text");
await sw.FlushAsync();
}
}
GitHub 倉庫
編輯
是否using var sw = new StreamWriter(...)有效似乎取決于所使用的 HTTP 客戶端。如果使用 Chrome,則控制臺中會出現錯誤,并且不會顯示任何文本。如果使用 Postman,則沒有錯誤,并且回應包含“一些普通文本”。
uj5u.com熱心網友回復:
不是 100% 肯定,但我會說這是因為在方法完成之后但在寫入和重繪 流的任務實際運行之前處理了流,因為回傳的只是承諾做這些事情。
沒有它的原因using是因為從未呼叫過 dispose 。
它與 一起作業的原因await using是因為流的處理也包含在任務的一部分中。
至于為什么客戶端會有所作為,可能是因為它被流式傳輸到一個并直接執行到另一個。
uj5u.com熱心網友回復:
我真的應該查看 ASP.NET Core 的控制臺輸出,其中包含以下堆疊跟蹤:
System.InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpResponseStream.Flush()
at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder)
at System.IO.StreamWriter.Dispose(Boolean disposing)
at System.IO.TextWriter.Dispose()
所以問題是StreamWriter.Dispose同步重繪 底層流,默認不允許同步寫操作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/419198.html
標籤:
