我正在创建任务并传递取消令牌,我希望在用户按下与单独类中的表格相关联的按钮时使用取消令牌来取消任务。
我目前有以下代码:
[Form] Class A
private CancellationToken _cancellationToken;
private void Start()
{
_cancellationToken = new CancellationToken();
_otherService.Start(data, ref_cancellationToken);
}
private void BtnCancelOperation_Click(object sender, EventArgs e)
{
var cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = cancellationTokenSource.Token;
cancellationTokenSource.Cancel(true); // I want this to cancel the operation started in **Class B**
}
[DLL] B类
public void Start(Data data, ref CancellationToken cancellationToken)
{
Task.Run(() => StartMainLoop(data), cancellationToken);
}
// I'm still not sure how to link this method to the cancellation.
private void CancellationReceived()
{
logger.Info("Task cancelled by user.");
}
此当前方法不起作用,我试图同时声明CancellationTokenSource,但这也没有效果。
在阅读其他问题/文档时,我的假设是我所做的步骤正确吗?显然,CancellationTokenSource应该告诉所有附加的CancellationToken取消。