Home > front end >  How to add all awaits ViewModel to Task.WhenAll
How to add all awaits ViewModel to Task.WhenAll

Time:04-12

How to add this three awaits in a Task.WhenAll() but with a return value of my model, cause without adding it in a WhenAll() I can get the return of my model. But when adding it in Task.WhenAll() all I get is some AsyncState, id properties.

var _pending = await _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Pending);
var _cancel = await _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Cancel);
var _completed = await _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Completed);

List<Task> taskList = List<Task<StatusLookup>>();
taskList.Add(_lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Pending));
taskList.Add(_lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Cancel));
taskList.Add(_lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Completed));

var result = await Task.WhenAll(taskList);

Thank you

CodePudding user response:

You can read the results after WhenAll returns. You can use either await (calling it again on a completed task doesn't do anything) or read it out of Result.

var pendingTask = _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Pending);
var cancelTask = _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Cancel);
var completedTask = _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Completed);

await Task.WhenAll( new [] { pendingTask, cancelTask, completedTask } );

_pending = pendingTask.Result;
_cancel = cancelTask.Result;
_complete = completedTask.Result;

You might even be able to skip the WhenAll. This will give you a slightly different behavior but it would probably work just as well:

var pendingTask = _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Pending);
var cancelTask = _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Cancel);
var completedTask = _lookupService.GetFirstOrDefaultAsync<StatusLookup>(x => x.Code == LookupConstants.Completed);

_pending = await pendingTask;
_cancel = await cancelTask;
_complete = await completedTask;

CodePudding user response:

You have an answer here: https://jeremylindsayni.wordpress.com/2019/03/11/using-async-await-and-task-whenall-to-improve-the-overall-speed-of-your-c-code/

To tell it in the least possible words, you should assign tasks (without await) to variables. Then wait for them with WhenAll and finally read their results in their Result property.

  • Related