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

时间:2018-10-03 07:49:49

标签: c# asynchronous continuewith

当其他任务可能永远持续运行时,如何正确使用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.
});

1 个答案:

答案 0 :(得分:3)

您可以运行另一个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