I have some code in my business logic layer which consume some repositories which in turn use a DbContext (in the data layer). Most of the code is async. At some point in my business logic, I call several async method of the repositories at once (
And I ran into an error
A second operation started on this context before a previous asynchronous operation completed
My point of view is, the business logic should not care/be aware on how the repositories do their job, so it should be able to use parallelism on async Task if "it pleases so".
So I would like to be able to lock in an async/await friendly way the critical moment where
A second operation should wait until the
previous asynchronous operation complete.
How can this be done?
Current work-arround: forget Task.WhenAll use await like TPL don't even exist
var postsResult = await _IUserLogic.GetActivePostsAsync(); var usersResult = await _IUserLogic.SearchUsersWithPostAsync(viewModel.Name, viewModel.PostId);
var postsTask = _IUserLogic.GetActivePostsAsync(); var usersTask = _IUserLogic.SearchUsersWithPostAsync(viewModel.Name, viewModel.PostId); await Ask.WhenAll(postsTask , usersTask ); var postsResult = postsTask.Result; var usersResult = usersTask.Result;
Each thread needs its own DbContext because DbContext is not thread safe. However, there are a few work-arounds here.