Krumelur
Krumelur

Reputation: 33048

Is Task.Run() the same as creating Task instance and then Start() it?

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.

Upvotes: 3

Views: 702

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456417

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.

Upvotes: 3

Related Questions