I have some code to review:
Task.WhenAll(contracts.Select(x => Task.Run(() =>
{
// here some 30 lines of synchronous code
}))).GetAwaiter().GetResult();
My thought that this code is better to run synchronously in a plain foreach
as 30 lines of codes seem to me not too much CPU intensive operation. But I'm not very sure for that.
If an operation takes more that 50 ms to complete, it's better to run it asynchronously. Therefore, I have to measure the performance of it. But it is impossible to do while reviewing the pull request.
So, is the any other way to figure out whether the operation is really CPU intensive?
UPDATE:
If an operation takes more that 50 ms to complete, it's better to run it asynchronously.
I read it from Stephen Cleary's blog: https://blog.stephencleary.com/2013/04/ui-guidelines-for-async.html
There is no point in running CPU operations asynchronously at all, you just add a lot of overhead and use same CPU resource after that as well.
The point with asynchronous operations is that if you have to wait, then you don't need to block the tread, so it can do something else.
So even if the operation runs for 2 minutes of pure CPU, you don't win anything by calling it asynchronously.
Moreover you are just synchronously waiting for all the operations to complete anyway. So you can use your Task.Run
to run operations in parallel, but you don't need to do anything else about that.
As far as I know the only difference between just doing .Result
and .GetAwaiter().GetResult()
will be the type of exception you are getting.
So my point is: there is nothing async in your code already, so there is nothing to measure.