简体   繁体   English

Task.Delay在等待时是否浪费系统资源?

[英]Does Task.Delay waste system resources while it is waiting?

I'm trying to run a piece of code periodically with time intervals in between. 我正在尝试定期运行一段代码,时间间隔介于两者之间。 There might be multiple number of such code pieces running simultaneously so I turned to Task.Run to utilize asynchronous method calls and parallelism. 可能有多个此类代码块同时运行,因此我转向Task.Run以利用异步方法调用和并行性。 Now I wonder how should I implement the time intervals! 现在我想知道我应该如何实现时间间隔!

The straight forward way would be using Task.Delay like this: 直截了当的方式是使用Task.Delay如下所示:

var t = Task.Run(async delegate 
{ 
   await Task.Delay(1000); 
   return 42; 
});

But I wonder if doing so is the right way to do it since I believe all the Task.Delay does is to sleep the thread and resume it once the period is over (even though I'm not sure). 但我想知道这样做是不是正确的方法,因为我相信所有的Task.Delay都是睡眠线程并在句点结束后恢复它(即使我不确定)。 If this is the case then system has to pay for the task's thread resources even when the task is not running. 如果是这种情况,则即使任务未运行,系统也必须为任务的线程资源付费。

If this is the case, is there any way to run a task after a period of time without wasting any system resources? 如果是这种情况,有没有办法在一段时间后运行任务而不浪费任何系统资源?

Task.Delay does not cause the thread to sleep. Task.Delay不会导致线程休眠。 It uses a timer. 它使用计时器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM