Reputation: 1940
Of the 1000 tasks that have created , lets say only few (10) will complete, based on taskCompletionSource being successful in some other part of code. That means ProcessWorkItemAsync
finished will be printed 10 times only.
code :
for (var i = 0;i<1000; i++)
{
Task.Run(() => {
await ProcessWorkItemAsync();
Console.WriteLine("ProcessWorkItemAsync finished");
});
}
async Task<TaskCompletionSource<int>> ProcessWorkItemAsync()
{
return new TaskCompletionSource<int>();
}
Upvotes: 1
Views: 734
Reputation: 456887
Of the 1000 tasks that have created , lets say only few (10) will complete, based on taskCompletionSource being successful in some other part of code. That means ProcessWorkItemAsync finished will be printed 10 times only.
The code you posted doesn't have that behavior. The posted code will print "ProcessWorkItemAsync finished"
1000 times and all tasks will complete almost immediately. For the rest of this answer, I'm going to address the questions and ignore the code.
Is there an CPU over head of 990 task not completing and being in a limbo ?
No.
From what I have read , the thread will not be blocked, it will be returned to the thread pool, so from CPU perspective there does not appear to be any overhead.Anything else I am missing ?
Tasks are not threads. The fact that you have 1000 tasks in no way implies that there are or were 1000 threads involved.
Task.Run
does queue work to the thread pool, but when using asynchronous tasks with Task.Run
, that thread pool thread is returned to the thread pool anytime await
has to asynchronously wait. Whether the tasks complete or not is immaterial.
Is there Memory overhead ?
Yes. Tasks are objects just like any other reference type. They can be rooted just like any other reference type. And if they are never cleaned up (completed), they can be a resource leak just like any other reference type.
because of the call stacks being stored, since dot net has to keep track where to get back to. I assume these call stacks will be stored in the heap and incur a memory cost ?
Sort of. Call stacks are not captured or stored. The task only stores its continuations. Logically, you could think of this as a "call stack" but it only has a depth of 1. So, each task will keep alive any code that await
s it.
Upvotes: 4