我正在生成用于处理不同方法的多个任务。虽然某些方法可以达到目的,但我需要取消该任务。为此,我正在生成CancellationTokenSource并将其分配给每个任务。当任务完成时,我可以取消该任务。
在此实施期间,我收到类似'The CancellationTokenSource has been disposed.'
的错误
我已经在那里设置了调试器并检查了它的值,但是我无法找到此错误的根本原因。我们如何处理这个错误?我需要您最好的建议。
//Create class for handle cancellationTokenSource with each Task individually
public class tempTask
{
public string symbolName { get; set; }
public System.Threading.CancellationTokenSource cts { get; set; }
public Task task { get; set; }
}
//Declaration of CTS, Binding Object Class
public static System.Threading.CancellationTokenSource _tokenSource = new System.Threading.CancellationTokenSource();
public static Dictionary<string, System.Threading.CancellationTokenSource> test = new Dictionary<string, System.Threading.CancellationTokenSource>();
public static List<tempTask> tempTasks = new List<tempTask>();
// In first method : creating object of CTS and sending as a parameter
_tokenSource = new System.Threading.CancellationTokenSource();
startAddToPosition(_tokenSource, _symbolName);
//In startAddToPosition method : Assigning TokenSource to Task
public static async void startAddToPosition(System.Threading.CancellationTokenSource cts1, string symbolName)
{
try
{
Task t1 = Task.Run(() => Task.Delay(30000, cts1.Token), cts1.Token);
tempTask tmp = new tempTask
{
cts = cts1,
task = t1,
symbolName = symbolName
};
tempTasksList.Add(tmp);
}
catch(Exception ex)
{
//Below line throwing an error `'The CancellationTokenSource has been disposed.'
var symName = test.FirstOrDefault(q => q.Value.Token == ex.CancellationToken).Key;
generateRealPosition(symName);
}
}
那么,在处理此问题的代码中我缺少添加的任何部分吗?