JasinCole
Well-known member
- Joined
- Feb 16, 2023
- Messages
- 66
- Programming Experience
- 1-3
Me again, but this time I know what my issue is. How to best handle this situation?
Using the following code is causing an exception because I am trying to use the dbContext in another operation while another thread is using dbContext and that operation hasn't finished.
What's the best way to create a scoped instance so I am not accessing the dbContext from two threads at the same time? I don't really need the UnitOfWork here because I am not trying to write to the database(failures don't require rollbacks), but I would still like to keep the dashboard in sync, such that any task that reads from the database should be correct across all information displayed. That is why I am creating task and then WhenAll finish either as a failure or success.
Using the following code is causing an exception because I am trying to use the dbContext in another operation while another thread is using dbContext and that operation hasn't finished.
What's the best way to create a scoped instance so I am not accessing the dbContext from two threads at the same time? I don't really need the UnitOfWork here because I am not trying to write to the database(failures don't require rollbacks), but I would still like to keep the dashboard in sync, such that any task that reads from the database should be correct across all information displayed. That is why I am creating task and then WhenAll finish either as a failure or success.
C#:
public partial class HomePageViewModel : ViewModelBase
{
[ObservableProperty] private Task<IEnumerable<Lgract>>? _accounts;
[ObservableProperty] private Task<(decimal, decimal, decimal)>? _agingPayables;
public HomePageViewModel(IUnitOfWork srvc) : base(srvc) // Dependency Injection UnitOfWork - UnitOfWork holds the dbContext that gets passed to all the repository objects
{
InitializeAsync().SafeFireAndForget();
}
private async Task InitializeAsync()
{
var task = new Task[]
{
LoadAccountBalances(), // <- uses dbContext inside Srvc scope
LoadAgingPayables() // <- causes exception because different thread is using the samedbContext inside Srvc scope
};
await Task.WhenAll(task);
}
private async Task<IEnumerable<Lgract>> LoadAccountBalances()
{
...
return await Srvc.Lgracts.GetAccountsByRecnumAsync(accounts.Select(act => act.Number).ToList());
}
private async Task<(decimal due7Days, decimal due30Days, decimal overdue30Days)> LoadAgingPayables()
{
...
return (dueInSevenDays, dueInThirtyDays, thirtyDaysOverdue);
}
}