I have a problem with cancellation token that doesn't work. I created a simple code example of my actual project. This is my scenario:
class Program
{
static void Main(string[] args)
{
var taskCheker = new TaskChecker();
taskCheker.Test();
Console.ReadKey();
}
}
public class TaskChecker
{
public void Test()
{
var list = Enumerable.Range(0, 10);
Parallel.ForEach(list, (item) =>
{
CancellationTokenSource cancellationToken = new CancellationTokenSource();
cancellationToken.CancelAfter(1000);
try
{
var task = Task.Run(() =>
{
Console.WriteLine($"item: {item} with thread: {Thread.CurrentThread.ManagedThreadId} started");
LongTask();
Console.WriteLine($"item: {item} with thread: {Thread.CurrentThread.ManagedThreadId} finished");
}, cancellationToken.Token);
Task.WaitAll(new[] { task });
}
catch (TaskCanceledException)
{
Console.WriteLine("TaskCanceledException runned");
}
catch (Exception)
{
Console.WriteLine("Exception runned");
}
});
Console.WriteLine("Parallel finished");
Console.ReadKey();
}
public void LongTask()
{
Thread.Sleep(2000);
}
}
I have a Parallel.Foreach
that calls inner Task
for each item. Inner Task
has a cancellation token with 1 second. Inner Task
call a LongTask
method that it takes 2 seconds, and I expect that all of my inner tasks throw timeout. But all of them call and after 2 seconds will complete. So I don't know why my cancellation token doesn't work.
Thank you so much to your help