I have a loop and within the loop I'm doing:
await Task.Delay(1000, ct).ContinueWith(async _ =>
{
await SecondMethodAsync(ct);
});
The second method gets an entity using EF, sets some properties and saves the entity back to the datastore by calling await SaveChangesAsync()
on the DbContext
.
The above should wait for 1s and then continue with the second method. With the above implementation I get the following exception:
A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.
When I change the above to:
await Task.Delay(1000, ct);
await SecondMethodAsync(ct);
Everything works fine.
What is the difference with the above 2 snippets and how do I get to make the first snippet work?