Is there a reason for an async Task<> foo()
to take time being created? (Just created, awaiting it takes even another chunk of time).
When profiling my web service performance I noticed that the mere creation of the task takes a considerable amount of time (in the order of the hundreds of milliseconds).
//DB intensive async tasks, just creating them all takes 600ms-1800ms
Task<Egg> eggTask = FryEggs(2);
Task<Bacon> baconTask = FryBacon(3);
Task<Toast> toastTask = ToastBread(2);
//actually awaiting them takes some hundreds of milliseconds more...
await Task.WhenAll(eggTask, baconTask, toastTask);
The functions in question don't do heavy synchronous work before the first await inside them, so I can't find a compelling reason for them to work this way. Something in this fashion:
async Task<Object> FryEggs(){
VeryLightweightSynchronousWork();
await BottleneckingIOWork();
}
I have tried using Task.Factory.StartNew
and it does return immediately:
async Task<Object> FryEggs(){
var res = await Task.Factory.StartNew(async => {
VeryLightweightSynchronousWork();
return await BottleneckingIOWork();
}
return await res;
}
I don't understand this behaviour.
I actually don't care too much about my specific case, I want to understand why, on a reference-based point of view, should this happen. My current understanding is that a Task starts as soon as it is called, but it should do so asynchronously. So, why would the main thread wait so much for an async task to be created?
Thank you in advance!