Skip to content

Why 'await Task.Delay' executes synchronously in some cases? #114809

Answered by AustinWise
Dreamescaper asked this question in Q&A
Discussion options

You must be logged in to vote

Async methods execute synchronously until they encounter the first await on a non-completed task. In this case the race condition is caused by the Task returned by Task.Delay completing before GetBatchedDataAsync checks that it is completed. GetBatchedDataAsync continues to execute synchronously and then fails to find the data in pendingBatches.

A trace of execution looks something like this:

  1. Thread A: Calls BatchExecutionHelper.GetAsync
  2. Thread A: Calls BatchExecutionHelper.GetBatchedDataAsync
  3. Thread A: Calls Task.Delay, which creates a DelayPromise. The DelayPromise creates a Timer that will complete the DelayPromise.
  4. Thread B: Enough time has past that the timer callback is executed, m…

Replies: 4 comments 6 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@Clockwork-Muse
Comment options

@Dreamescaper
Comment options

Comment options

You must be logged in to vote
3 replies
@Dreamescaper
Comment options

@Clockwork-Muse
Comment options

@Dreamescaper
Comment options

Comment options

You must be logged in to vote
1 reply
@Dreamescaper
Comment options

Answer selected by Dreamescaper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants