1

I am not sure how C# works when assigning tasks to thread.

I want to verify something. Is it guaranteed that at any time, each task is being handled by one and only one thread, regardless of what that task is doing, even if its just stopped or did Thread.currentThread().sleep(), that thread will not go and serve any other task ? So its 1:1 between the thread and the tasks ? Regardless of what the task is doing, even if its just sleeping, or whether the task was called via Task.Run or await Task.Run etc ?

Steve
  • 213,761
  • 22
  • 232
  • 286
xander
  • 1,427
  • 2
  • 16
  • 26

1 Answers1

3

There are a couple of cases I'm aware of where tasks can be re-entrant. One is where one task is waiting for another task to complete, and that first task hasn't yet started. It makes sense for the new task to be started on the current thread in that case... sort of. It does raise some nasty worries about locking and any other thread-local context.

It's also possible (apparently) for Task.Factory.StartNew to execute a new task "inline", if the scheduler deems it appropriate - but the schedulers built into .NET don't do this.

See this other Stack Overflow question which includes more detailed response from Stephen Toub (on the PFX team).

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Thank you so much. So if both tasks are started and none not yet returned, it is 100% impossible that they both be executing on the same thread ? – xander Jan 31 '13 at 15:30
  • @xander: See my edit - it's hard to give any absolutes given that you can build your own task schedulers. Reading Stephen Toub's reply carefully is probably the best bet. Note that as far as I'm aware, tasks don't *change* threads - so if the two tasks have already started on separate threads, they won't both later end up on the same thread. – Jon Skeet Jan 31 '13 at 15:33
  • Thank you so much for the reference. The only thing I am a bit unsure here is: "if the two tasks have already started on separate threads". Is the default behavior is to start tasks on separate threads, without the special case you mentioned before ? – xander Jan 31 '13 at 15:39