据我所知,如果我在我的 Startup.cs
中使用 services.AddControllers()
或 services.AddMvc()
扩展“MVC 将自动绑定(bind)操作方法中的任何 CancellationToken
参数。
我有以下 TestController
和 TestService
作为 transient 服务。
根据这些信息,当自动绑定(bind)CancellationToken
IsCancellationRequested
时,我作为参数传递的 token 是否也会被取消?
public class TestController : ControllerBase
{
private readonly ITestService _testService;
public TestController(ITestService testService)
{
_testService = testService;
}
[HttpGet, ActionName("Get")]
public async Task<IActionResult> GetAsync(CancellationToken cancellationToken)
{
await _testService.GetAsync(cancellationToken);
return Ok();
}
}
public class TestService : ITestService
{
public async Task GetAsync(CancellationToken cancellationToken)
{
//I also send the cancellationToken as a parameter to external API calls
}
}
最佳答案
when the auto-binded CancellationToken IsCancellationRequested will the tokens that I have passed as parameters be also canceled?
通过将 CancellationToken 注入(inject)您的操作方法,它将自动绑定(bind)到请求的 HttpContext.RequestAborted 标记。在用户刷新浏览器或单击“停止”按钮取消请求后,原始请求将中止并返回一个 TaskCancelledException,该异常通过 MVC 过滤器管道传播回来,并备份中间件管道。然后,您可以检查 IsCancellationRequested 的值并优雅地退出操作。在这种情况下,不需要将CancellationToken作为参数传递。
如果您想取消异步任务,因为 CancellationTokens 是由 CancellationTokenSource 创建的轻量级对象。当 CancellationTokenSource 被取消时,它会通知 CancellationToken 的所有消费者。因此,您可以调用 Cancel() 方法来取消任务。
检查以下示例:
var cts = new CancellationTokenSource();
//cts.CancelAfter(5000);//Request Cancel after 5 seconds
_logger.LogInformation("New Test start");
var newTask = Task.Factory.StartNew(state =>
{
int i = 1;
var token = (System.Threading.CancellationToken)state;
while (true)
{
Console.WriteLine(i);
i++;
if (i == 10)
{
cts.Cancel(); //call the Cancel method to cancel.
}
_logger.LogInformation("thread running " + DateTime.Now.ToString());
Thread.Sleep(1000);
token.ThrowIfCancellationRequested();
}
}, cts.Token, cts.Token);
try
{
newTask.Wait(10000);
}
catch
{
Console.WriteLine("Catch:" + newTask.Status);
}
_logger.LogInformation("Test end");
更多关于使用CancellationToken的详细信息,请查看以下文章:
Using CancellationTokens in ASP.NET Core MVC controllers
关于asp.net-core - 我可以在 AspNetCore WebAPI 中将 CancellationToken 作为参数传递吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64431862/
相关文章:
html - 使一个 div 填充具有未指定尺寸的表格单元格的整个宽度和高度
python - 'google-api-python-client' distribution 在
javascript - 错误 : Jmeter: Typed variable declarati
android - x + 宽度必须 <= bitmap.width()
reactjs - typescript 错误对象的类型为 'unknown'
angular - 如何限制 NgSelect 下拉面板中显示的项目数?
vue.js - 使用 vue 的故事书 - SassError : Undefined varia