当另一个任务可能永远 运行 继续时,如何正确使用 ContinueWith?

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

当其他任务有可能永远运行继续时,如何正确使用ContinueWith

示例:

task是无限的,但我只想等她特定的时间:

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

你可以运行另一个Task.Delay等待

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

但是你应该使用一种方法来停止第一个任务,如何超时或使用 CancellationTokenSource