Adv*_*axi 7 c# asp.net-core asp.net-core-webapi asp.net-core-2.0 angular
我有以下两个应用
我正在使用Angular的HttpClient向API 发出GET请求,如下所示
this.subscription = this.httpClient.get('api/Controller/LongRunningProcess')
.subscribe((response) =>
{
// Handling response
});
Run Code Online (Sandbox Code Playgroud)
API控制器的LongRunningProcess方法具有以下代码
[HttpGet]
[Route("LongRunningProcess")]
public async Task<IActionResult> LongRunningProcess(CancellationToken cancellationToken)
{
try
{
// Dummy long operation
await Task.Factory.StartNew(() =>
{
for (int i = 0; i < 10; i++)
{
// Option 1 (Not working)
if (cancellationToken.IsCancellationRequested)
break;
// Option 2 (Not working)
cancellationToken.ThrowIfCancellationRequested();
Thread.Sleep(6000);
}
}, cancellationToken);
}
catch (OperationCanceledException e)
{
Console.WriteLine($"{nameof(OperationCanceledException)} thrown with message: {e.Message}");
}
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
现在,我想取消这个长期运行的过程,因此我正在退订客户端,如下所示
// On cancel button's click
this.subscription.unsubscribe();
Run Code Online (Sandbox Code Playgroud)
上面的代码将取消请求,我可以在浏览器的“ 网络”选项卡中看到它被取消,如下所示
但这不会使API的LongRunningProcess方法中的 IsCancellationRequested变为true,因此该操作将继续进行。
[注]:无论方案1和方案2中的API方法,如果我做邮递员使用一个电话,甚至没有工作。
问题:有什么方法可以取消LongRunningProcess方法的操作?
在这种情况下你不需要中断,只需像这样使用
[HttpGet]
[Route("LongRunningProcess")]
public async Task<IActionResult> LongRunningProcess(CancellationToken cancellationToken)
{
for (int i = 0; i < 10; i++)
{
cancellationToken.ThrowIfCancellationRequested();
// Dummy long operation
await Task.Factory.StartNew(() => Thread.Sleep(60000));
}
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
您可以在这里阅读更多内容
| 归档时间: |
|
| 查看次数: |
332 次 |
| 最近记录: |