是否有多个 Task.Run 等待而不返回的开销?

Is there an overhead of multiple Task.Run that awaits without returning?

在已创建的 1000 个任务中,假设只有少数 (10) 个将完成,基于 taskCompletionSource 在代码的其他部分成功。这意味着 ProcessWorkItemAsync finished 将只打印 10 次。

代码:

for (var i = 0;i<1000; i++)
{
     Task.Run(() => {
      await ProcessWorkItemAsync(); 
      Console.WriteLine("ProcessWorkItemAsync finished");
     }); 

}

async Task<TaskCompletionSource<int>> ProcessWorkItemAsync()
{
    return new TaskCompletionSource<int>();
}
  1. 是否有 CPU 超过 990 项任务未完成并处于不确定状态?
    • 根据我的阅读,线程不会被阻塞,它会返回到线程池,所以从 CPU 的角度来看似乎没有任何 overhead.Anything 否则我是失踪 ?
  2. 是否有内存开销?
    • 因为存储了调用堆栈,因为 dot net 必须跟踪返回的位置。
    • 我假设这些调用堆栈将存储在堆中并产生内存成本?

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.

您发布的代码没有这种行为。发布的代码将打印 "ProcessWorkItemAsync finished" 1000 次,所有任务将几乎立即完成。对于此答案的其余部分,我将解决问题并忽略代码。

Is there an CPU over head of 990 task not completing and being in a limbo ?

没有

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 ?

任务不是线程。您有 1000 个任务这一事实绝不意味着涉及 1000 个线程。

Task.Run 对线程池进行队列工作,但是当使用带有 Task.Run 的异步任务时,该线程池线程随时返回到线程池 await 必须异步等待.任务完成与否并不重要。

Is there Memory overhead ?

是的。任务就像任何其他引用类型一样是对象。它们可以像任何其他引用类型一样植根。如果它们从未被清理(完成),它们可以 a resource leak 就像任何其他引用类型一样。

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 ?

有点。不会捕获或存储调用堆栈。该任务仅存储其延续。从逻辑上讲,您可以将其视为 "call stack",但它的深度仅为 1。因此,每个任务都会使 await 包含它的任何代码保持活动状态。