0

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

1 回答 1

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

但是您应该使用一种方法来停止 First Task Some How 超时或使用 CancellationTokenSource

于 2018-10-03T07:56:51.523 回答