Reputation: 16831
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?
Upvotes: 3
Views: 4230
Reputation: 456437
Task.Delay
does not cause the thread to sleep. It uses a timer.
Upvotes: 11