1

我不确定在将任务分配给线程时 C# 是如何工作的。

我想验证一些东西。是否保证在任何时候,每个任务都由一个且只有一个线程处理,无论该任务正在做什么,即使它刚刚停止或执行了 Thread.currentThread().sleep(),该线程也不会去并服务于任何其他任务?那么它在线程和任务之间是 1:1 的吗?不管任务在做什么,即使它只是在睡觉,或者任务是通过 Task.Run 还是 await Task.Run 等调用的?

4

1 回答 1

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

于 2013-01-31T15:29:42.630 回答