【发布时间】:2018-04-24 15:20:08
【问题描述】:
在我的一个项目中,我需要为我们为客户添加的每个新条目添加任务,并且这些任务是使用 LongRunning 选项创建的,因此当我们收到该客户的任何请求时,所有这些请求都需要处理仅限后端服务。
下面是示例代码片段,我将客户添加到任务中,当客户不想与我们关联时,我们从任务中删除
公共词典 _cancellationTokenSourcesForChannels = new Dictionary();
public void AddCustomerToTask(int custId, CancellationToken cancelToken)
{
var cust = custSvc.SessionFactory.OpenSession().Get<Customer>(custId);
var custModel = new CustomerModel().FromCustomer(cust);
var tokenSource = new CancellationTokenSource();
var taskPoller = new Task(() => WindowsService.Start(custModel), tokenSource.Token,
TaskCreationOptions.LongRunning);
taskPoller.Start();
//Maintaining list of cancellationTokenSource in Dictionary
if (_cancellationTokenSourcesForChannels == null)
_cancellationTokenSourcesForChannels = new Dictionary<int, CancellationTokenSource>();
if (_cancellationTokenSourcesForChannels.ContainsKey(custId))
_cancellationTokenSourcesForChannels.Remove(custId);
_cancellationTokenSourcesForChannels.Add(custId, tokenSource);
}
public void RemoveCustomerFromTask(int custId)
{
CancellationTokenSource currentToken;
if (_cancellationTokenSourcesForChannels.ContainsKey(custId))
{
_cancellationTokenSourcesForChannels.TryGetValue(custId, out currentToken);
currentToken?.Cancel();
}
if (_cancellationTokenSourcesForChannels.ContainsKey(custId))
_cancellationTokenSourcesForChannels.Remove(custId);
}
所以,我的问题是,当我请求删除不想关联的客户时,我调用 RemoveCustomerFromTask(custId),然后基本上代码正在尝试取消该客户的任务。但有趣的是,它还取消了为其他客户创建的所有任务。
有人可以帮我解决我的问题吗?
当我调用 RemoveCustomerFromTask 方法时,我将取消令牌列表保存到字典中以删除。
【问题讨论】:
标签: c# task-parallel-library cancellationtokensource cancellation-token