1 year ago
#252249
Julien Martin
Calculate execution time in async method
I've a BackgroundService
that execute a DoWork
method.
In ExecuteAsync
method, I've a list of 400 items, I measured elapsed time for all process like this:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var listItems = await _myService.GetAll();
var sw = Stopwatch.StartNew();
List<Task> l = new();
listItems.AsParallel().ForAll(x => l.Add(DoWork(x)));
await Task.WhenAll(l);
sw.Stop();
_logger.LogInformation($"{sw.Elapsed.TotalMilliseconds} ms");
}
It's works fine, globally process take 5-6 seconds.
My DoWork
method (I simplified as much as possible):
private async Task DoWork(string item)
{
var sw = Stopwatch.StartNew();
var somethingResult = await otherServiceClass.DoSomething(item);
var stuffResult = await otherServiceClass.DoStuff(item);
sw.Stop();
_logger.LogInformation($"{sw.Elapsed.TotalMilliseconds} ms");
}
I would like measured each call of DoWork
method, but in log the elapsed time for each call varies between 2-3 seconds.
How is it possible knowing that the overall processing takes 5-6 seconds?
If I change listItems.AsParallel().ForAll(x => l.Add(DoWork(x)));
by foreach(var item in listItems)
, each call of DoWork method take 50-60 ms !
Is it AsParallel.ForAll
which is problematic?
How I can do this knowing that I want to user listItems.AsParallel().ForAll
for process.
UPDATE Here an example of DoSomething method. DoSomething method is declared in my application layer, and calls repository method to retrieve data from database :
public async Task<item> GetItemsIds()
{
return = await _myRepository.GetIdsItems(some parameters...);
}
Here GetIdsItems method :
public async Task<items> GetIdsItems(some parameters...)
{
return await _context.Collection.Where(condition....).FirstOrDefaultAsync().ConfigureAwait(false);
}
My backgroundservice run as Windows Service.
c#
.net
asynchronous
async-await
stopwatch
0 Answers
Your Answer