1

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"); 
        }
    }
}

enter image description here

Andrey Zhminka
  • 243
  • 4
  • 16

1 Answers1

0

You're testing an incorrect case.

You've created a timer that registers a periodic callback - you need to dispose the timer for it to stop invoking that method periodically. Right now you're just cancelling each invocation, not cancelling the callback.

Instead, if you want a normal cancellation - that would be the case if you were doing some work via a spawned thread / task / threadpoool call. A usage of cancellation token makes sense there - you've got some long running work you wish to cancel.

Vivek
  • 2,103
  • 17
  • 26