Jake
Jake

Reputation: 11430

Is Task.ContinueWith() guaranteed to run?

Suppose I have some async task that can sometimes run fast and sometimes slow,

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

Is the callback in Task.ContinueWith() guaranteed to run in the above scenario?

Upvotes: 3

Views: 340

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456507

will there be a chance that callback will not be called if _Work completes very quickly?

No. Continuations passed to ContinueWith will always be scheduled. If the task is already complete, they will be scheduled immediately. The task uses a thread-safe kind of "gate" to ensure that a continuation passed to ContinueWith will always be scheduled; there is a race condition (of course) but it's properly handled so that the continuation is always scheduled regardless of the results of the race.

Upvotes: 6

Related Questions