I'm new to async and I'm trying to create async WPF MVVM application with MVVM Light framework and have a problem with "A second operation started on this context before a previous asynchronous operation completed..."
In my program, when I clik button new View is shown and if there is a message with data ViewModel receives it and fills the appropriate controls with data, if not it is ready to add new ones. Therefore in the CTOR there is method GetInitialValues() and messenger (MVVMLight).
When openinig the View its ViewModel CTOR looks like in the code below So in CTOR:
- I provide a UOF using AutoFac. Injected UOF uses one dbContext for all Repositories per MyViewModel (acc. to the video: https://youtu.be/rtXpYpZdOzM?t=1328, I introduced Async methods in generic repository and its interface)
- Getting initial values for combobox lists etc.
- Registering Messenger using MVVMLight
The thing is that during GetInitialValues() async method is executing the CTOR goes to the end and Messenger received the Notification and switch the execution path to the handler OnSomeEntitySent()
Taking into consideration that we are on the one Thread generated by GetInitialValues() and that it was interrupted by OnSomeEntitySent() I got the Exeption: "A second operation started on this context before a previous asynchronous operation completed"
I tried to use in GetInitialValues() Task.WhenAll (I thought it will block the eventhandler to the end of the method) but the same situation appears - "A second operation started on this context before a previous asynchronous operation completed..."
public MyViewModel(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
Task.Run(async () => await GetInitialValues());
Messenger.Default.Register<SomeEntity>(this, OnSomeEntitySent);
}
private async Task GetInitialValues()
{
CboList1= await unitOfWork.SomeEntity1.GetAllAsync().ConfigureAwait(false);
CboList2= await unitOfWork.SomeEntity1.GetAllAsync().ConfigureAwait(false);
CboList3= await unitOfWork.SomeEntity1.GetAllAsync().ConfigureAwait(false);
}
private async void OnSomeEntitySent()
{
SomeEntity4 = await unitOfWork.SomeEntity4.GetAsync().ConfigureAwait(false);
SomeEntity5 = await unitOfWork.SomeEntity5.GetAsync().ConfigureAwait(false);
}
I do not know how to handle following things:
- How to await OnSomeEntitySent() eventhandler to wait until GetInitialValues() method goes to the end.
- How to make parallel tasks when using UOF based on one dbContext (i.e. using Task.WhenAll)
Thank you in advance for help.