Is Task.Factory.StartNew() guaranteed to create at least one new thread?

前端 未结 6 1948
一生所求
一生所求 2021-01-24 14:38

I understand that the TPL does not necessarily create a new thread for every task in a parallel set, but does it always create at least one? eg:

private void MyF         


        
相关标签:
6条回答
  • 2021-01-24 15:20

    That's up to whatever the current default TaskScheduler is. You can just about envisage someone doing something horrific like implementing a SynchronousTaskScheduler that executes the task body during QueueTask and sets it to complete before returning.

    Assuming you're not letting someone else muck about with your task schedulers, you shouldn't have to worry about it.

    0 讨论(0)
  • 2021-01-24 15:24

    In short: Yes, this is guranteed.

    Longer: If StartNew() does not create a new thread, it will reuse another: Either by it being free, or by queueing.

    0 讨论(0)
  • 2021-01-24 15:25

    DoSomethingTimely will get called very quickly, but what does that have to do with creating a new thread, or adding the task to a queue?

    0 讨论(0)
  • 2021-01-24 15:27

    Yes, it will hit very shortly after dispatching the task to run.

    No, it will not create a new thread, but claim one. When they say it doesn't always create a new thread, they are referring to the fact that it re-uses threads from a thread pool.

    The size of the pool is based on the number of CPU cores detected. But it will always contain at least 1 thread. ;)

    0 讨论(0)
  • 2021-01-24 15:38

    It depends on what you mean by "immediately" but I think it's reasonable to assume that the TPL isn't going to hijack your currently executing thread to synchronously run the code in your task, if that's what you mean. At least not with the normal scheduler... you could probably write your own scheduler which does do so, but you can normally assume that StartNew will schedule the task rather than just running it inline.

    0 讨论(0)
  • 2021-01-24 15:40

    Your main question and the question in your code are completely different questions. But the answers to the two questions are:

    1) No, there's no guarantee a thread will be started. What is created and started is a task. Ultimately, some thread will have to execute that task, but whether one will be created is unspecified. An existing thread could be re-used.

    2) It depends what you mean by "immediately". Strictly speaking, there is no timeliness guarantee. But you have told the system to execute that task, and it will at least start it as soon as it finishes everything it considers more important. Strict fairness or timeliness is not guaranteed.

    0 讨论(0)
提交回复
热议问题