1

Dears, I have a method which loads few tables. I would like to execute them all in the same time .. not one after another..

my code below:

    public async Task FillViewModelDataAsync(out IndexViewModel vm)
    { 
        vm.Areas = await _context.Areas.Where(x => x.IsDisabled == false).ToDictionaryAsync(x => x.Id, y => y.Name);
        vm.SubAreas = await _context.SubAreas.Where(x => x.IsDisabled == false).ToDictionaryAsync(x => x.Id, y => y.Name);
        vm.WorkCenters = await _context.Workcenters.Where(x => x.IsDisabled == false).ToDictionaryAsync(x => x.Id, y => y.Name);
        vm.Priorities = await _context.Priorities.Where(x => x.IsDisabled == false).ToDictionaryAsync(x => x.Id, y => y.Name);
        vm.Departments = await _context.DepartmentToWorkcenters.Get().Where(x => x.IsDisabled == false).ToDictionaryAsync(x => x.Id, y => y.Name);
    }

I guess I should create a list of tasks and later wait.all()... am I right? How to do it correctly?

MatR
  • 225
  • 1
  • 12
  • it's `await Task.WhenAll(...)` you want to google, there are tons of examples online – René Vogt Jul 13 '20 at 13:54
  • `Task.WhenAll`, and just make sure to use a different db context for each task. Using the same `_context` for multiple concurrently running tasks will get you into trouble. – Theodor Zoulias Jul 13 '20 at 14:29
  • No it won't, because they won't run in parallel -- that's why they are awaitable, they await a mutex to synchronize access to the database. @rychu151 even if you run these in parallel (`Task.WhenAll` or `Parallel.Invoke` or whatever), they'll still run one at a time if you run them on the same context. – Blindy Jul 13 '20 at 15:11

0 Answers0