3

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. Now I wonder how should I implement the time intervals!

The straight forward way would be using Task.Delay like this:

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). 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?

Mehran
  • 15,593
  • 27
  • 122
  • 221

1 Answers1

11

Task.Delay does not cause the thread to sleep. It uses a timer.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 1
    Would you say that `Task.Delay` is the right/optimum way of postponing the start of a task? As in the above code? Could you please include a reference as an evidence for your word? Thanks. – Mehran Oct 08 '13 at 11:29
  • 1
    @user2586804: No. @Mehran: If you have a *periodic* action (e.g., every 5 seconds the action should start), then it's probably better to just use a periodic timer to kick it off; if you have a periodic delay (e.g., do something, wait 5 seconds, do something, wait 5 seconds, etc), then `Task.Delay` would be cleaner. AFAIK there's no official documentation that `Delay` uses a timer, but because it's asynchronous you know it *can't* block the calling thread. – Stephen Cleary Oct 08 '13 at 11:34
  • 2
    @Mehran See this thread where they talk about the implementation of Task.Delay: http://stackoverflow.com/questions/17378548/what-it-costs-to-use-task-delay – Matthew Watson Oct 08 '13 at 11:35
  • OK, so it's not causing it to sleep, it carries on of course, but at some point there may be a `Wait()` and then it'll sleep? It's not at any point spin-waiting, wasting resources, which is OP's concern. – user2586804 Oct 08 '13 at 11:36
  • 1
    @user2586804: There is no point where a thread is blocked or spin-waiting until the timeout. In a properly-written UI app, there won't be a `Wait` (which *would* cause a thread to be blocked). – Stephen Cleary Oct 08 '13 at 11:43
  • Yes, so to answer another part of his question (and I know he's accepted the answer so he obviously gets the implications, but I'm not quite there yet), this `Task.Delay` will or wont waste resources? – user2586804 Oct 08 '13 at 12:46
  • @user2586804: It will not waste resources. – Stephen Cleary Oct 08 '13 at 12:53