-2

I need to run multiple task to access to database and to wait to all task finished to obtain the result and assign it to my viewmodel, i try many sample but i have never have the result, any help please, this my code

var model = new AggregationViewModel();
var loadDataTasks = new Task[]
{
    Task.Run(async () =>model.Alive =  await _repository.GetCountAsync<filter>(Predicate)),
    Task.Run(async () => model.Delay = await _repository.GetCountAsync<Flight>(predicate.And(x => x.Status == "refused")))
};
try
{
    await Task.WhenAll(loadDataTasks);
    foreach (var item in loadDataTasks)
    {

    }
}
catch (Exception ex)
{
}
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98
user1428798
  • 1,534
  • 3
  • 24
  • 50

2 Answers2

0

Check this out:

 var task1 = _repository.GetCountAsync<filter>(Predicate);
 var task2 = _repository.GetCountAsync<Flight>(predicate.And(x => x.Status == "refused"));

 await Task.WhenAll(task1, task2); //wait both tasks to finish

 model.Alive = await task1;
 model.Delay = await task2;

PS: the function, which the above code is placed, is needed to be async for the above scenario.

Derviş Kayımbaşıoğlu
  • 28,492
  • 4
  • 50
  • 72
0

Try this code:

var model = new AggregationViewModel();

//----------------------------------------
var tasks = new List<Task<int>>();
//Add CountA
tasks.Add(_repository.GetCountAsync<filter>(Predicate));
//Add CountB
tasks.Add(_repository.GetCountAsync<Flight>(predicate.And(x => x.Status == "refused")));

//----------------------------------------
// Create a task with "allTasks" name to wait to complete all tasks
Task allTasks = Task.WhenAll(tasks);
try {
    // Wait to compelete "allTask"
     allTasks.Wait();
}
catch(AggregateException) 
{}

//----------------------------------------
//Working on the results

if (allTasks.Status == TaskStatus.RanToCompletion) {
   model.CountA=allTasks.Result[0]
   model.CountB=allTasks.Result[1]
}
// Display information on faulted tasks.
else {
    foreach (var t in tasks) {
        Console.WriteLine("Task {0}: {1}", t.Id, t.Status);
     }
}
Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98