我已经部署了一个连续Azure WebJob,其中包含从队列消息中触发的过程。
public Task Automation([QueueTrigger("automqueue")] string message, TextWriter log, CancellationToken token)
{
....
}
该过程包含一个CancellationToken
,系统将其用于here。
当用户想要取消该过程时,是否有任何编程方式触发此CancellationToken
?
我的自动化需要分配资源才能完成,有时可能需要几个小时才能完成。这就是为什么用户可能想要取消该过程并开始另一个过程的原因。
我可以使用已经拥有的CancellationToken
还是需要实施自定义解决方案?
答案 0 :(得分:1)
CancelationToken
仅用于关闭通知,它在所有Process实例之间共享,并且不能用于其他原因。
并且它仅用于读取,您无法手动更改它,因此也许您可以创建一个新的CancellationTokenSource
并将这些令牌合并为一个令牌,如果其中任何一个令牌被取消,则将被取消。
这是我的代码。
public static void ProcessQueueMessage(
[QueueTrigger("queue2")] string message,
ILogger logger, CancellationToken token
)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
string flag;
CancellationTokenSource compositeTokenSource =
CancellationTokenSource.CreateLinkedTokenSource(
tokenSource.Token, token);
if (message.Equals("shutdown"))
{
logger.LogInformation(message);
tokenSource.Cancel();
flag = compositeTokenSource.Token.IsCancellationRequested.ToString();
logger.LogInformation(flag);
}
else {
logger.LogInformation(message);
flag = compositeTokenSource.Token.IsCancellationRequested.ToString();
logger.LogInformation(flag);
}
}
如果消息等于“ shutdown”,则将执行方法Cancel()
。这样,复合令牌的属性IsCancellationRequested
将为true
。
希望这对您有帮助,如果您仍有疑问,请告诉我。