【问题标题】:Is Task.ContinueWith() guaranteed to run?Task.ContinueWith() 是否保证运行?
【发布时间】:2019-10-02 22:37:55
【问题描述】:

假设我有一些异步任务,有时运行得快有时慢,

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 不会被调用?
  • @EricLippert 是的,假设 SomeMethod() 在程序的另一部分被多次调用。

标签: c# async-await task


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 2016-06-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    相关资源
    最近更新 更多