Task.ContinueWith()保证会执行吗?

3
假设我有一些异步任务,有时可能运行快,有时可能运行慢,
public Random seed = new Random();
private async Task<string> _Work()
{
    int time = seed.Next(0, 5000);
    string result = string.Format("Worked for {0} milliseconds", time);
    await Task.Delay(time);
    return result;
}

public void SomeMethod()
{
    _Work(); // starts immediately? Am I right?

    // since _Work() will be executed immediately before ContinueWith() is executed,
    // will there be a chance that callback will not be called if _Work completes very quickly,
    // like before ContinueWith() can be scheduled?
    _Work().ContinueWith(callback)
}

在上述情况下,Task.ContinueWith() 中的回调函数是否有保障会被执行?

你为什么认为如果_Work很快完成,callback不会被调用? - Kenneth K.
@EricLippert 是的,假设在程序的另一部分中多次调用了SomeMethod()。 - Jake
1个回答

6

如果_Work很快完成,回调函数有可能不会被调用吗?

不会。传递给ContinueWith的延续将始终被安排。如果任务已经完成,它们将立即被安排。任务使用一种线程安全的“门”类型来确保传递给ContinueWith的延续将始终被安排;存在竞争条件(当然),但是它们被正确处理,以便无论竞争的结果如何,延续始终被安排。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接