1

I could find out that, Task.Run executes always on threads from .NET Framework threads pool (TaskScheduler.Default). I suppose, that it is the same with Task.Delay, but I'm not sure.

MSDN says for Task.Delay only:

Creates a task that will complete after a time delay

Therefore the question: Where (in which synchronization context) runs Task.Delay?

Rekshino
  • 6,954
  • 2
  • 19
  • 44
  • Have a look at [Task vs Thread differences](https://stackoverflow.com/questions/13429129/task-vs-thread-differences). *"(A Task) it's really just "the promise of a result in the future""* – Liam Nov 19 '18 at 15:47

1 Answers1

3

Task.Delay doesn't run anywhere. It just creates a task that completes after the specified time. Unlike Task.Run it's not accepting a delegate of yours to run somewhere. Most tasks won't represent the execution of some method on another thread. Task.Run is one of few methods that do that.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • For it completes after specified time, it should run specified time, or? – Rekshino Nov 19 '18 at 15:44
  • @Rekshino It's not "running" anything. It's creating a task that will be marked as completed after the specified time. It's not sitting there running code during that time. It's *doing nothing* during that time. – Servy Nov 19 '18 at 15:45
  • I'm reminded of a [recent comment](https://stackoverflow.com/questions/53376516/can-asp-net-run-background-tasks-simultaneously?noredirect=1#comment93629380_53376516) :) – Liam Nov 19 '18 at 15:48
  • @Servy Hmm.. I need to think about Wait() and await for `Task.Delay` for task, which does not run. – Rekshino Nov 19 '18 at 15:49
  • @Liam The OP here can't see that as it's deleted, but yes. – Servy Nov 19 '18 at 15:49
  • @Rekshino It's almost always wrong to synchronously block on a task. All the moreso when that task is `Delay`. – Servy Nov 19 '18 at 15:50
  • @Servy But Task.Delay(N).Wait() block our synchronisation context right? – Rekshino Nov 19 '18 at 15:56
  • 2
    @Rekshino Yes. And that's basically never correct. It's the waiting that does the blocking, not the `Delay`. – Servy Nov 19 '18 at 16:00
  • 1
    @Servy Can we say, that Task.Delay is an "empty" Task, which being finished in N ms and running in synchronisation context where it is called? – Rekshino Nov 19 '18 at 16:00
  • 1
    @Rekshino No, you can't say that it's "running in the synchronization context where it's called" because **it's not running anywhere**. `Task.Delay` doesn't involve running code. It creates a task that will be completed at the specified time *and does not involve any code running during that interval of time*. – Servy Nov 19 '18 at 16:01
  • @Servy Now.. I have understood! :) I have voted up the key comment. May be it makes sense to copy it to the answer. – Rekshino Nov 19 '18 at 16:16