Search code examples
c#asynchronouscontinuewith

How to use ContinueWith properly when the other task may continue running forever?


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

Solution

  • 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