0

If I have for example the following code:

Task task = Task.Factory.StartNew(() =>
{
    work1();
    work2();
    work3();
    work4();
    ...
}, token);

if (!task.Wait(10 * 1000))
{
    ...timeout
}

Is it possible to accomplish a behavior where if I get a timeout the logic inside the time-outed task will get cancelled as well? for example: if work1 took 11 seconds and then finished, I want to make sure all the works afterwards will not be executed.

omriman12
  • 1,644
  • 7
  • 25
  • 48

1 Answers1

0

You can insert ThrowIfCancellationRequested() before every method call:

Task task = Task.Factory.StartNew(() =>
{
    token.ThrowIfCancellationRequested();
    work1();

    token.ThrowIfCancellationRequested();
    work2();

    token.ThrowIfCancellationRequested();
    work3();

    token.ThrowIfCancellationRequested();
    work4();
    ...
}, token);

if (!task.Wait(TimeSpan.FromSeconds(10))
{
    tokenSource.Cancel();
    // handle cancel case
} else {
    // handle done case
}

This way, if this work is not getting done in 10 seconds, you will stop execution of code inside your task.

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101