Why avoid synchronous reading
All I/O operations in Core are asynchronous. The server has been implementedStream
Interface, this interface has both synchronous and asynchronous methods.
When performing I/O operations, the asynchronous method should be used to avoid blocking threads in the thread pool.
If the thread pool thread is blocked, the server may be unable to process more requests, causing rapidPerformance degradation。
EspeciallyWhen the client upload speed is slow, synchronous reading willblockThe thread is completed until the entire request body is read.
How to avoid synchronous reading
The wrong way
The following code example uses a synchronization methodReadToEnd
, causing the thread to be blocked:
public class BadStreamReaderController : Controller
{
[HttpGet("/contoso")]
public ActionResult<ContosoData> Get()
{
var json = new StreamReader().ReadToEnd();
return <ContosoData>(json);
}
}
In this code,Get
Method synchronously reads the entire HTTP request body into memory. If the client uploads slowly, the application willblockIn this read operation, efficiency decreases.
The correct way to do it
Using an asynchronous methodReadToEndAsync
, can avoid blocking threads:
public class GoodStreamReaderController : Controller
{
[HttpGet("/contoso")]
public async Task<ActionResult<ContosoData>> Get()
{
var json = await new StreamReader().ReadToEndAsync();
return <ContosoData>(json);
}
}
This code uses an asynchronous reading method, which will not block threads during the reading process.Improve performanceand response speed.
Things to note when reading form data
The wrong way
use, synchronous reading will be performed internally, causing the thread to be blocked:
public class BadReadController : Controller
{
[HttpPost("/form-body")]
public IActionResult Post()
{
var form = ;
Process(form["id"], form["name"]);
return Accepted();
}
}
The correct way to do it
useReadFormAsync
, perform asynchronous reading:
public class GoodReadController : Controller
{
[HttpPost("/form-body")]
public async Task<IActionResult> Post()
{
var form = await ();
Process(form["id"], form["name"]);
return Accepted();
}
}
This approach uses asynchronous method to read form data, which can effectively avoid blocking thread pool resources.
in conclusion
In Core development, the framework should be consistent with the asynchronous operation mode and avoid using synchronous methods to read HTTP request text.
This can effectively improve the performance and response speed of the application and avoid sharp performance degradation caused by blockage.