0

How to use ContinueWith properly when there is a chance that the other task may continue running forever?

Example:

task is infinite but I'm only would like to wait for her only for specific amount of time:

var task = Task.Factory.StartNew(() => 
{
    //Small chance for infinite loop
});

task.ContinueWith(t => {
    //We would still like to get here after a certion amount of time eventualy.
});
Shahar Shokrani
  • 7,598
  • 9
  • 48
  • 91
  • Short answer is you don't... it doesn't make any sense, if you want a possible never-ending-task and you want to `ContinueWith`, then you don't have the right tool for the job – TheGeneral Oct 03 '18 at 07:50
  • @Saruman but i want to protect myself not to wait forever – Shahar Shokrani Oct 03 '18 at 07:52
  • How exactly are you using the `.ContinueWith` here ? Do you check the `t` for error or just want to execute some business logic ? – Fabjan Oct 03 '18 at 07:56
  • https://blogs.msdn.microsoft.com/pfxteam/2011/11/10/crafting-a-task-timeoutafter-method/ – Access Denied Oct 03 '18 at 07:56

1 Answers1

3

You can run another Task.Delay to wait

var task = Task.Factory.StartNew(() => 
        {
            //Small chance for infinite loop
        });
        var delayTask = Task.Delay(2000); // A wait task 
        Task.WhenAny(delayTask,task).ContinueWith((t) =>
        {
            //check which task has finished 
        });

But you should use a way to stop First Task Some How timeout it or use CancellationTokenSource

Milad
  • 379
  • 1
  • 16