我正在尝试将Web API和取消令牌协同工作,但由于某些原因它似乎没有很好地发挥作用.
这是我的Web API的代码.它包含取消令牌属性和方法
public class TokenCancellationApiController : ApiController { private static CancellationTokenSource cTokenSource = new CancellationTokenSource(); // Create a cancellation token from CancellationTokenSource private static CancellationToken cToken = cTokenSource.Token; // Create a task and pass the cancellation token [HttpGet] public string BeginLongProcess() { string returnMessage = "The running process has finished!"; try { LongRunningFunc(cToken, 6); } catch (OperationCanceledException cancelEx) { returnMessage = "The running process has been cancelled."; } finally { cTokenSource.Dispose(); } return returnMessage; } [HttpGet] public string CancelLongProcess() { // cancelling task cTokenSource.Cancel(); return "Cancellation Requested"; } private static void LongRunningFunc(CancellationToken token, int seconds) { Console.WriteLine("Long running method"); for (int j = 0; j < seconds; j++) { Thread.Sleep(1000); if (token.IsCancellationRequested) { Console.WriteLine("Cancellation observed."); throw new OperationCanceledException(token); // acknowledge cancellation } } Console.WriteLine("Done looping"); } }
我有以下HTML代码:
Web API方法被称为罚款.当我单击按钮开始漫长的过程,然后点击取消时,我希望它取消漫长的过程,并返回一条警告消息,告诉我它被取消了.
但事实并非如此.虽然有一个令牌取消请求,但它似乎没有注册,并且长进程一直运行直到它完成.
任何人都可以告诉我为什么这不起作用,因为我想要它?