问题描述
我有方法:
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");
}
我想在新的Task中启动此方法.我可以像这样开始新任务
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));
或这个
var task = Task.Run(new Action(Method));
但是Task.Run()
和Task.Factory.StartNew()
之间没有任何区别.创建Task实例后,他们两个都立即使用ThreadPool并启动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?
推荐答案
第二种方法Task.Run
已在.NET Framework的更高版本中(在.NET 4.5中)引入.
The second method, Task.Run
, has been introduced in a later version of the .NET framework (in .NET 4.5).
但是,第一种方法Task.Factory.StartNew
使您有机会为要创建的线程定义很多有用的东西,而Task.Run
没有提供此功能.
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.
为避免这种情况,您可以做的一件事是在单独的线程中运行任务.一个新创建的线程专用于此任务,一旦完成任务便会被销毁.您 无法通过Task.Run
来实现,而您可以使用Task.Factory.StartNew
进行操作,如下所示:
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);
此处所述:
Task.Run(someAction);
Task.Factory.StartNew(someAction,
CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
这篇关于Task.Run()和Task.Factory.StartNew()有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!