In my app I need to force stop a task, when it exceeds the preset timeout. Until I see that i can only cancel the thread via token but the thread is still will be run in the background. Even if I throw an exception after a timeout, the thread continues to run...
There is example of code and result:
internal class Program
{
private static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
var cls = new CancellationTokenSource();
Task task = Task.Factory.StartNew(state =>
{
Console.WriteLine("Task Started" );
Timer timer = new Timer(TimeElapsed, cls, 3000, 0);
Thread.Sleep(6000);
Console.WriteLine("End Task");
}, cls.Token);
}
Console.ReadLine();
}
private static void TimeElapsed(object obj)
{
try
{
var cls = (CancellationTokenSource)obj;
cls.Cancel();
cls.Token.ThrowIfCancellationRequested();
}
catch (Exception)
{
Console.WriteLine("Aborted");
}
}
}