3

This is what I use all the time:

var task = Task.Run(DoSomething);

I wonder if would make a difference if I used this instead:

var task = new Task(DoSomething);
task.Start();

MSDN says:

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static Task.Run(Action)

In the first case, the task is started immediately. That's an obvious difference but besides that it's not clear to me if there are any (relevant) differences.

MSDN does not say if the options used will be the same. For Task.Run() they document that it will use DenyChildAttach und that it will use the default scheduler.

However for Start() there is no word about the creation option it's using.

But there is another difference: Start() will use the current task scheduler and not the default one.

According to this answer here, current is not the same as default and current is not supposed to be used in combination with async/await, however I must admit that I do not fully understand the difference between the two and wonder if it is important when deciding Start() vs. Task.Run().

Long story short: seeing the differences, I'd like to know if they are relevant when used in combination with async/await? And if they are relevant, why is that? The MSN documentation only says that I probably want to use Task.Run() but they don't explain the why.

Community
  • 1
  • 1
Krumelur
  • 32,180
  • 27
  • 124
  • 263
  • 2
    What's your question? You've already identified many differences, noting that `Task.Run` is appropriate for async code and `Start` is not. – Stephen Cleary Apr 07 '16 at 18:55
  • @StephenCleary I updated the question to be clearer. I can see the differences but I don't know how/why they would matter. – Krumelur Apr 07 '16 at 18:59

1 Answers1

3

StartNew is analogous to the task constructor with Task.Start. I have a blog post that goes into detail with both the major problems of StartNew, both of which apply to the task constructor and Task.Start. In particular, the constructor doesn't understand asynchronous delegates, and Start uses the current scheduler by default instead of the default scheduler.

I also have a blog series (which is still not finished, sorry!) that walks through all the Task members (and related types) in detail, discussing which of them are best used in which situations. Interestingly, there is no use case for the Task constructor (discussion) or Task.Start (discussion) at all. There is always a better solution.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • _"StartNew is analogous to the task constructor with Task.Start"_ - that's good information. I read all about the shortcomings of `StartNew()`. – Krumelur Apr 07 '16 at 19:23