What is the difference between Task.Run() and Task.Factory.StartNew()
I have Method :
private static void Method()
{
Console.WriteLine("Method() started");
for (var i = 0; i < 20; i++)
{
Console.WriteLine("Method() Counter = " + i);
Thread.Sleep(500);
}
Console.WriteLine("Method() finished");
}
And I want to start this method in a new Task.
I can start new task like this
var task = Task.Factory.StartNew(new Action(Method));
or this
var task = Task.Run(new Action(Method));
But is there any difference between Task.Run() and Task.Factory.StartNew(). Both of them are using ThreadPool and start Method() immediately after creating instance of the Task. When we should use first variant and when second?
c# multithreading task-parallel-library
add a comment |
I have Method :
private static void Method()
{
Console.WriteLine("Method() started");
for (var i = 0; i < 20; i++)
{
Console.WriteLine("Method() Counter = " + i);
Thread.Sleep(500);
}
Console.WriteLine("Method() finished");
}
And I want to start this method in a new Task.
I can start new task like this
var task = Task.Factory.StartNew(new Action(Method));
or this
var task = Task.Run(new Action(Method));
But is there any difference between Task.Run() and Task.Factory.StartNew(). Both of them are using ThreadPool and start Method() immediately after creating instance of the Task. When we should use first variant and when second?
c# multithreading task-parallel-library
6
Actually, StartNew does not have to use the ThreadPool, see the blog I linked to in my answer. The problem isStartNewby default usesTaskScheduler.Currentwhich may be the thread pool but also could be the UI thread.
– Scott Chamberlain
Jul 17 '16 at 16:51
1
Possible duplicate of Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
– Ahmed Abdelhameed
Oct 26 '17 at 4:39
add a comment |
I have Method :
private static void Method()
{
Console.WriteLine("Method() started");
for (var i = 0; i < 20; i++)
{
Console.WriteLine("Method() Counter = " + i);
Thread.Sleep(500);
}
Console.WriteLine("Method() finished");
}
And I want to start this method in a new Task.
I can start new task like this
var task = Task.Factory.StartNew(new Action(Method));
or this
var task = Task.Run(new Action(Method));
But is there any difference between Task.Run() and Task.Factory.StartNew(). Both of them are using ThreadPool and start Method() immediately after creating instance of the Task. When we should use first variant and when second?
c# multithreading task-parallel-library
I have Method :
private static void Method()
{
Console.WriteLine("Method() started");
for (var i = 0; i < 20; i++)
{
Console.WriteLine("Method() Counter = " + i);
Thread.Sleep(500);
}
Console.WriteLine("Method() finished");
}
And I want to start this method in a new Task.
I can start new task like this
var task = Task.Factory.StartNew(new Action(Method));
or this
var task = Task.Run(new Action(Method));
But is there any difference between Task.Run() and Task.Factory.StartNew(). Both of them are using ThreadPool and start Method() immediately after creating instance of the Task. When we should use first variant and when second?
c# multithreading task-parallel-library
c# multithreading task-parallel-library
edited Jul 12 '17 at 19:53
Christos
44.3k84678
44.3k84678
asked Jul 17 '16 at 16:34
Sergiy LichenkoSergiy Lichenko
6822610
6822610
6
Actually, StartNew does not have to use the ThreadPool, see the blog I linked to in my answer. The problem isStartNewby default usesTaskScheduler.Currentwhich may be the thread pool but also could be the UI thread.
– Scott Chamberlain
Jul 17 '16 at 16:51
1
Possible duplicate of Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
– Ahmed Abdelhameed
Oct 26 '17 at 4:39
add a comment |
6
Actually, StartNew does not have to use the ThreadPool, see the blog I linked to in my answer. The problem isStartNewby default usesTaskScheduler.Currentwhich may be the thread pool but also could be the UI thread.
– Scott Chamberlain
Jul 17 '16 at 16:51
1
Possible duplicate of Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
– Ahmed Abdelhameed
Oct 26 '17 at 4:39
6
6
Actually, StartNew does not have to use the ThreadPool, see the blog I linked to in my answer. The problem is
StartNew by default uses TaskScheduler.Current which may be the thread pool but also could be the UI thread.– Scott Chamberlain
Jul 17 '16 at 16:51
Actually, StartNew does not have to use the ThreadPool, see the blog I linked to in my answer. The problem is
StartNew by default uses TaskScheduler.Current which may be the thread pool but also could be the UI thread.– Scott Chamberlain
Jul 17 '16 at 16:51
1
1
Possible duplicate of Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
– Ahmed Abdelhameed
Oct 26 '17 at 4:39
Possible duplicate of Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
– Ahmed Abdelhameed
Oct 26 '17 at 4:39
add a comment |
5 Answers
5
active
oldest
votes
The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5).
However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn't provide this.
For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.
One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);
As it is stated here:
So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the
new Task.Run method. This in no way obsoletes Task.Factory.StartNew,
but rather should simply be thought of as a quick way to use
Task.Factory.StartNew without needing to specify a bunch of
parameters. It’s a shortcut. In fact, Task.Run is actually
implemented in terms of the same logic used for Task.Factory.StartNew,
just passing in some default parameters. When you pass an Action to
Task.Run:
Task.Run(someAction);
that’s exactly equivalent to:
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
4
I have a piece of code where the statementethat’s exactly equivalent todoes not hold.
– Emaborsa
Sep 11 '17 at 10:05
4
@Emaborsa I would appreciate If you could post this piece of code and elaborate your argument. Thanks in advance !
– Christos
Sep 11 '17 at 10:10
2
@Emaborsa You could create a gist, gist.github.com, and share it. However, except from sharing this gist, please specify how did you get to the outcome that the phrasetha's exactly equivalent todoes not hold. Thanks in advance. It would be nice to explain with comment on your code. Thanks :)
– Christos
Sep 12 '17 at 7:17
6
It's also worth mentioning that Task.Run unwrap nested task by default. I recommend to read this article about major differences: blogs.msdn.microsoft.com/pfxteam/2011/10/24/…
– Pawel Maga
Nov 7 '17 at 14:59
1
@The0bserver nope, it isTaskScheduler.Default. Please have a look here referencesource.microsoft.com/#mscorlib/system/threading/Tasks/….
– Christos
Jan 21 at 18:13
|
show 4 more comments
See this blog article that describes the difference. Basically doing:
Task.Run(A)
Is the same as doing:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
add a comment |
The Task.Run got introduced in newer .NET framework version and it is recommended.
Starting with the .NET Framework 4.5, the Task.Run method is the
recommended way to launch a compute-bound task. Use the StartNew
method only when you require fine-grained control for a long-running,
compute-bound task.
The Task.Factory.StartNew has more options, the Task.Run is a shorthand:
The Run method provides a set of overloads that make it easy to start
a task by using default values. It is a lightweight alternative to the
StartNew overloads.
And by shorthand I mean a technical shortcut:
public static Task Run(Action action)
{
return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}
add a comment |
According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:
I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :)
StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.
Here are the actual reasons:
- Does not understand async delegates. This is actually the same as
point 1 in the reasons why you would want to use StartNew. The problem
is that when you pass an async delegate to StartNew, it’s natural to
assume that the returned task represents that delegate. However, since
StartNew does not understand async delegates, what that task actually
represents is just the beginning of that delegate. This is one of the
first pitfalls that coders encounter when using StartNew in async
code.
- Confusing default scheduler. OK, trick question time: in the
code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);
private static void A() { }
Well, you know it’s a trick question, eh? If you answered “a thread
pool thread”, I’m sorry, but that’s not correct. “A” will run on
whatever TaskScheduler is currently executing!
So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.
In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().
For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
add a comment |
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38423472%2fwhat-is-the-difference-between-task-run-and-task-factory-startnew%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5).
However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn't provide this.
For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.
One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);
As it is stated here:
So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the
new Task.Run method. This in no way obsoletes Task.Factory.StartNew,
but rather should simply be thought of as a quick way to use
Task.Factory.StartNew without needing to specify a bunch of
parameters. It’s a shortcut. In fact, Task.Run is actually
implemented in terms of the same logic used for Task.Factory.StartNew,
just passing in some default parameters. When you pass an Action to
Task.Run:
Task.Run(someAction);
that’s exactly equivalent to:
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
4
I have a piece of code where the statementethat’s exactly equivalent todoes not hold.
– Emaborsa
Sep 11 '17 at 10:05
4
@Emaborsa I would appreciate If you could post this piece of code and elaborate your argument. Thanks in advance !
– Christos
Sep 11 '17 at 10:10
2
@Emaborsa You could create a gist, gist.github.com, and share it. However, except from sharing this gist, please specify how did you get to the outcome that the phrasetha's exactly equivalent todoes not hold. Thanks in advance. It would be nice to explain with comment on your code. Thanks :)
– Christos
Sep 12 '17 at 7:17
6
It's also worth mentioning that Task.Run unwrap nested task by default. I recommend to read this article about major differences: blogs.msdn.microsoft.com/pfxteam/2011/10/24/…
– Pawel Maga
Nov 7 '17 at 14:59
1
@The0bserver nope, it isTaskScheduler.Default. Please have a look here referencesource.microsoft.com/#mscorlib/system/threading/Tasks/….
– Christos
Jan 21 at 18:13
|
show 4 more comments
The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5).
However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn't provide this.
For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.
One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);
As it is stated here:
So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the
new Task.Run method. This in no way obsoletes Task.Factory.StartNew,
but rather should simply be thought of as a quick way to use
Task.Factory.StartNew without needing to specify a bunch of
parameters. It’s a shortcut. In fact, Task.Run is actually
implemented in terms of the same logic used for Task.Factory.StartNew,
just passing in some default parameters. When you pass an Action to
Task.Run:
Task.Run(someAction);
that’s exactly equivalent to:
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
4
I have a piece of code where the statementethat’s exactly equivalent todoes not hold.
– Emaborsa
Sep 11 '17 at 10:05
4
@Emaborsa I would appreciate If you could post this piece of code and elaborate your argument. Thanks in advance !
– Christos
Sep 11 '17 at 10:10
2
@Emaborsa You could create a gist, gist.github.com, and share it. However, except from sharing this gist, please specify how did you get to the outcome that the phrasetha's exactly equivalent todoes not hold. Thanks in advance. It would be nice to explain with comment on your code. Thanks :)
– Christos
Sep 12 '17 at 7:17
6
It's also worth mentioning that Task.Run unwrap nested task by default. I recommend to read this article about major differences: blogs.msdn.microsoft.com/pfxteam/2011/10/24/…
– Pawel Maga
Nov 7 '17 at 14:59
1
@The0bserver nope, it isTaskScheduler.Default. Please have a look here referencesource.microsoft.com/#mscorlib/system/threading/Tasks/….
– Christos
Jan 21 at 18:13
|
show 4 more comments
The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5).
However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn't provide this.
For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.
One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);
As it is stated here:
So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the
new Task.Run method. This in no way obsoletes Task.Factory.StartNew,
but rather should simply be thought of as a quick way to use
Task.Factory.StartNew without needing to specify a bunch of
parameters. It’s a shortcut. In fact, Task.Run is actually
implemented in terms of the same logic used for Task.Factory.StartNew,
just passing in some default parameters. When you pass an Action to
Task.Run:
Task.Run(someAction);
that’s exactly equivalent to:
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
The second method, Task.Run, has been introduced in a later version of the .NET framework (in .NET 4.5).
However, the first method, Task.Factory.StartNew, gives you the opportunity to define a lot of useful things about the thread you want to create, while Task.Run doesn't provide this.
For instance, lets say that you want to create a long running task thread. If a thread of the thread pool is going to be used for this task, then this could be considered an abuse of the thread pool.
One thing you could do in order to avoid this would be to run the task in a separate thread. A newly created thread that would be dedicated to this task and would be destroyed once your task would have been completed. You cannot achieve this with the Task.Run, while you can do so with the Task.Factory.StartNew, like below:
Task.Factory.StartNew(..., TaskCreationOptions.LongRunning);
As it is stated here:
So, in the .NET Framework 4.5 Developer Preview, we’ve introduced the
new Task.Run method. This in no way obsoletes Task.Factory.StartNew,
but rather should simply be thought of as a quick way to use
Task.Factory.StartNew without needing to specify a bunch of
parameters. It’s a shortcut. In fact, Task.Run is actually
implemented in terms of the same logic used for Task.Factory.StartNew,
just passing in some default parameters. When you pass an Action to
Task.Run:
Task.Run(someAction);
that’s exactly equivalent to:
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
edited Jan 13 '18 at 7:26
Michael Randall
34.8k83868
34.8k83868
answered Jul 17 '16 at 16:38
ChristosChristos
44.3k84678
44.3k84678
4
I have a piece of code where the statementethat’s exactly equivalent todoes not hold.
– Emaborsa
Sep 11 '17 at 10:05
4
@Emaborsa I would appreciate If you could post this piece of code and elaborate your argument. Thanks in advance !
– Christos
Sep 11 '17 at 10:10
2
@Emaborsa You could create a gist, gist.github.com, and share it. However, except from sharing this gist, please specify how did you get to the outcome that the phrasetha's exactly equivalent todoes not hold. Thanks in advance. It would be nice to explain with comment on your code. Thanks :)
– Christos
Sep 12 '17 at 7:17
6
It's also worth mentioning that Task.Run unwrap nested task by default. I recommend to read this article about major differences: blogs.msdn.microsoft.com/pfxteam/2011/10/24/…
– Pawel Maga
Nov 7 '17 at 14:59
1
@The0bserver nope, it isTaskScheduler.Default. Please have a look here referencesource.microsoft.com/#mscorlib/system/threading/Tasks/….
– Christos
Jan 21 at 18:13
|
show 4 more comments
4
I have a piece of code where the statementethat’s exactly equivalent todoes not hold.
– Emaborsa
Sep 11 '17 at 10:05
4
@Emaborsa I would appreciate If you could post this piece of code and elaborate your argument. Thanks in advance !
– Christos
Sep 11 '17 at 10:10
2
@Emaborsa You could create a gist, gist.github.com, and share it. However, except from sharing this gist, please specify how did you get to the outcome that the phrasetha's exactly equivalent todoes not hold. Thanks in advance. It would be nice to explain with comment on your code. Thanks :)
– Christos
Sep 12 '17 at 7:17
6
It's also worth mentioning that Task.Run unwrap nested task by default. I recommend to read this article about major differences: blogs.msdn.microsoft.com/pfxteam/2011/10/24/…
– Pawel Maga
Nov 7 '17 at 14:59
1
@The0bserver nope, it isTaskScheduler.Default. Please have a look here referencesource.microsoft.com/#mscorlib/system/threading/Tasks/….
– Christos
Jan 21 at 18:13
4
4
I have a piece of code where the statemente
that’s exactly equivalent to does not hold.– Emaborsa
Sep 11 '17 at 10:05
I have a piece of code where the statemente
that’s exactly equivalent to does not hold.– Emaborsa
Sep 11 '17 at 10:05
4
4
@Emaborsa I would appreciate If you could post this piece of code and elaborate your argument. Thanks in advance !
– Christos
Sep 11 '17 at 10:10
@Emaborsa I would appreciate If you could post this piece of code and elaborate your argument. Thanks in advance !
– Christos
Sep 11 '17 at 10:10
2
2
@Emaborsa You could create a gist, gist.github.com, and share it. However, except from sharing this gist, please specify how did you get to the outcome that the phrase
tha's exactly equivalent to does not hold. Thanks in advance. It would be nice to explain with comment on your code. Thanks :)– Christos
Sep 12 '17 at 7:17
@Emaborsa You could create a gist, gist.github.com, and share it. However, except from sharing this gist, please specify how did you get to the outcome that the phrase
tha's exactly equivalent to does not hold. Thanks in advance. It would be nice to explain with comment on your code. Thanks :)– Christos
Sep 12 '17 at 7:17
6
6
It's also worth mentioning that Task.Run unwrap nested task by default. I recommend to read this article about major differences: blogs.msdn.microsoft.com/pfxteam/2011/10/24/…
– Pawel Maga
Nov 7 '17 at 14:59
It's also worth mentioning that Task.Run unwrap nested task by default. I recommend to read this article about major differences: blogs.msdn.microsoft.com/pfxteam/2011/10/24/…
– Pawel Maga
Nov 7 '17 at 14:59
1
1
@The0bserver nope, it is
TaskScheduler.Default. Please have a look here referencesource.microsoft.com/#mscorlib/system/threading/Tasks/….– Christos
Jan 21 at 18:13
@The0bserver nope, it is
TaskScheduler.Default. Please have a look here referencesource.microsoft.com/#mscorlib/system/threading/Tasks/….– Christos
Jan 21 at 18:13
|
show 4 more comments
See this blog article that describes the difference. Basically doing:
Task.Run(A)
Is the same as doing:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
add a comment |
See this blog article that describes the difference. Basically doing:
Task.Run(A)
Is the same as doing:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
add a comment |
See this blog article that describes the difference. Basically doing:
Task.Run(A)
Is the same as doing:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
See this blog article that describes the difference. Basically doing:
Task.Run(A)
Is the same as doing:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
edited Nov 28 '17 at 9:37
Bugs
4,15992637
4,15992637
answered Jul 17 '16 at 16:48
Scott ChamberlainScott Chamberlain
99k25184326
99k25184326
add a comment |
add a comment |
The Task.Run got introduced in newer .NET framework version and it is recommended.
Starting with the .NET Framework 4.5, the Task.Run method is the
recommended way to launch a compute-bound task. Use the StartNew
method only when you require fine-grained control for a long-running,
compute-bound task.
The Task.Factory.StartNew has more options, the Task.Run is a shorthand:
The Run method provides a set of overloads that make it easy to start
a task by using default values. It is a lightweight alternative to the
StartNew overloads.
And by shorthand I mean a technical shortcut:
public static Task Run(Action action)
{
return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}
add a comment |
The Task.Run got introduced in newer .NET framework version and it is recommended.
Starting with the .NET Framework 4.5, the Task.Run method is the
recommended way to launch a compute-bound task. Use the StartNew
method only when you require fine-grained control for a long-running,
compute-bound task.
The Task.Factory.StartNew has more options, the Task.Run is a shorthand:
The Run method provides a set of overloads that make it easy to start
a task by using default values. It is a lightweight alternative to the
StartNew overloads.
And by shorthand I mean a technical shortcut:
public static Task Run(Action action)
{
return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}
add a comment |
The Task.Run got introduced in newer .NET framework version and it is recommended.
Starting with the .NET Framework 4.5, the Task.Run method is the
recommended way to launch a compute-bound task. Use the StartNew
method only when you require fine-grained control for a long-running,
compute-bound task.
The Task.Factory.StartNew has more options, the Task.Run is a shorthand:
The Run method provides a set of overloads that make it easy to start
a task by using default values. It is a lightweight alternative to the
StartNew overloads.
And by shorthand I mean a technical shortcut:
public static Task Run(Action action)
{
return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}
The Task.Run got introduced in newer .NET framework version and it is recommended.
Starting with the .NET Framework 4.5, the Task.Run method is the
recommended way to launch a compute-bound task. Use the StartNew
method only when you require fine-grained control for a long-running,
compute-bound task.
The Task.Factory.StartNew has more options, the Task.Run is a shorthand:
The Run method provides a set of overloads that make it easy to start
a task by using default values. It is a lightweight alternative to the
StartNew overloads.
And by shorthand I mean a technical shortcut:
public static Task Run(Action action)
{
return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}
edited Nov 16 '18 at 9:45
Rekshino
2,9522932
2,9522932
answered Jul 17 '16 at 16:36
Zein MakkiZein Makki
23.7k43249
23.7k43249
add a comment |
add a comment |
According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:
I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :)
StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.
Here are the actual reasons:
- Does not understand async delegates. This is actually the same as
point 1 in the reasons why you would want to use StartNew. The problem
is that when you pass an async delegate to StartNew, it’s natural to
assume that the returned task represents that delegate. However, since
StartNew does not understand async delegates, what that task actually
represents is just the beginning of that delegate. This is one of the
first pitfalls that coders encounter when using StartNew in async
code.
- Confusing default scheduler. OK, trick question time: in the
code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);
private static void A() { }
Well, you know it’s a trick question, eh? If you answered “a thread
pool thread”, I’m sorry, but that’s not correct. “A” will run on
whatever TaskScheduler is currently executing!
So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.
In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().
For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
add a comment |
According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:
I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :)
StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.
Here are the actual reasons:
- Does not understand async delegates. This is actually the same as
point 1 in the reasons why you would want to use StartNew. The problem
is that when you pass an async delegate to StartNew, it’s natural to
assume that the returned task represents that delegate. However, since
StartNew does not understand async delegates, what that task actually
represents is just the beginning of that delegate. This is one of the
first pitfalls that coders encounter when using StartNew in async
code.
- Confusing default scheduler. OK, trick question time: in the
code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);
private static void A() { }
Well, you know it’s a trick question, eh? If you answered “a thread
pool thread”, I’m sorry, but that’s not correct. “A” will run on
whatever TaskScheduler is currently executing!
So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.
In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().
For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
add a comment |
According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:
I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :)
StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.
Here are the actual reasons:
- Does not understand async delegates. This is actually the same as
point 1 in the reasons why you would want to use StartNew. The problem
is that when you pass an async delegate to StartNew, it’s natural to
assume that the returned task represents that delegate. However, since
StartNew does not understand async delegates, what that task actually
represents is just the beginning of that delegate. This is one of the
first pitfalls that coders encounter when using StartNew in async
code.
- Confusing default scheduler. OK, trick question time: in the
code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);
private static void A() { }
Well, you know it’s a trick question, eh? If you answered “a thread
pool thread”, I’m sorry, but that’s not correct. “A” will run on
whatever TaskScheduler is currently executing!
So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.
In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().
For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:
I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :)
StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.
Here are the actual reasons:
- Does not understand async delegates. This is actually the same as
point 1 in the reasons why you would want to use StartNew. The problem
is that when you pass an async delegate to StartNew, it’s natural to
assume that the returned task represents that delegate. However, since
StartNew does not understand async delegates, what that task actually
represents is just the beginning of that delegate. This is one of the
first pitfalls that coders encounter when using StartNew in async
code.
- Confusing default scheduler. OK, trick question time: in the
code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);
private static void A() { }
Well, you know it’s a trick question, eh? If you answered “a thread
pool thread”, I’m sorry, but that’s not correct. “A” will run on
whatever TaskScheduler is currently executing!
So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.
In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().
For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html
edited Nov 15 '18 at 21:36
answered Jun 18 '18 at 15:36
user8128167user8128167
2,79053651
2,79053651
add a comment |
add a comment |
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
add a comment |
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
add a comment |
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
answered Dec 29 '17 at 18:52
Devendra RusiaDevendra Rusia
11
11
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38423472%2fwhat-is-the-difference-between-task-run-and-task-factory-startnew%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
6
Actually, StartNew does not have to use the ThreadPool, see the blog I linked to in my answer. The problem is
StartNewby default usesTaskScheduler.Currentwhich may be the thread pool but also could be the UI thread.– Scott Chamberlain
Jul 17 '16 at 16:51
1
Possible duplicate of Regarding usage of Task.Start() , Task.Run() and Task.Factory.StartNew()
– Ahmed Abdelhameed
Oct 26 '17 at 4:39