當用戶向應用程式發出請求時,服務器將決議該請求,生成回應,然后將結果發送給客戶端,用戶可能會在服務器處理請求的時候中止請求,就比如說用戶跳轉到另一個頁面中獲取說關閉頁面,在這種情況下,我們希望停止所有正在進行的作業,以浪費不必要的資源,例如我們可能要取消SQL請求、http呼叫請求、CPU密集型操作等,
ASP.NET Core提供了HTTPContext.RequestAborted檢測客戶端何時斷開連接的屬性,我們可以通過IsCancellationRequested以了解客戶端是否中止連接,
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public async Task<WeatherForecast> Get()
{
CancellationToken cancellationToken = HttpContext.RequestAborted;
if (cancellationToken.IsCancellationRequested)
{
//TODO aborted request
}
return await GetWeatherForecasts(cancellationToken);
}
private async Task<WeatherForecast> GetWeatherForecasts(CancellationToken cancellationToken)
{
await Task.Delay(1000, cancellationToken);
return Array.Empty<WeatherForecast>();
}
}
當然我們可以通過如下代碼片段以引數形式傳遞
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet]
public async Task<WeatherForecast> Get(CancellationToken cancellationToken)
{
return await GetWeatherForecasts(cancellationToken);
}
private async Task<WeatherForecast> GetWeatherForecasts(CancellationToken cancellationToken)
{
await Task.Delay(1000, cancellationToken);
return Array.Empty<WeatherForecast>();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/24098.html
標籤:.NET Core
