Task.ContinueWith() 是否保证运行?

Jak*_*ake 3 c# task async-await

假设我有一些异步任务,有时可以快速运行,有时运行缓慢,

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)
}
Run Code Online (Sandbox Code Playgroud)

Task.ContinueWith() 中的回调是否保证在上述场景中运行?

Ste*_*ary 6

如果_Work 完成得很快,是否有可能不会调用回调?

不。传递给的继续ContinueWith将始终被安排。如果任务已经完成,他们将被立即安排。该任务使用一种线程安全的“门”来确保传递给的延续ContinueWith将始终被调度;有一个竞争条件(当然),但它得到了适当的处理,因此无论比赛结果如何,总是会安排继续。