Task.Start (), Task.Run () 및 Task.Factory.StartNew () 사용에 대해
방금 동일한 작업을 수행하는 TPL 사용에 관한 3 가지 루틴을 보았습니다. 코드는 다음과 같습니다.
public static void Main()
{
Thread.CurrentThread.Name = "Main";
// Create a task and supply a user delegate by using a lambda expression.
Task taskA = new Task( () => Console.WriteLine("Hello from taskA."));
// Start the task.
taskA.Start();
// Output a message from the calling thread.
Console.WriteLine("Hello from thread '{0}'.",
Thread.CurrentThread.Name);
taskA.Wait();
}
public static void Main()
{
Thread.CurrentThread.Name = "Main";
// Define and run the task.
Task taskA = Task.Run( () => Console.WriteLine("Hello from taskA."));
// Output a message from the calling thread.
Console.WriteLine("Hello from thread '{0}'.",
Thread.CurrentThread.Name);
taskA.Wait();
}
public static void Main()
{
Thread.CurrentThread.Name = "Main";
// Better: Create and start the task in one operation.
Task taskA = Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));
// Output a message from the calling thread.
Console.WriteLine("Hello from thread '{0}'.",
Thread.CurrentThread.Name);
taskA.Wait();
}
난 그냥 MS가 같은 TPL 그들은 때문에 모든 작업을 작업을 실행하는 3 개 가지 방법을 제공합니다 이유를 이해하지 않습니다 Task.Start()
, Task.Run()
그리고 Task.Factory.StartNew()
.
내게된다 텔 Task.Start()
, Task.Run()
그리고 Task.Factory.StartNew()
모두 같은 목적으로 사용하거나 서로 다른 의미를 가지고 있습니까?
때 하나 개 사용한다 Task.Start()
, 때 하나를 사용해야 Task.Run()
언제해야 하나 개 사용을 Task.Factory.StartNew()
?
예를 들어 시나리오별로 실제 사용법을 자세히 이해하도록 도와주십시오. 감사합니다.
Task.Run
Task.Factory.StartNew
특정 안전 인수 를 사용 하는 축약 형입니다 .
Task.Factory.StartNew(
action,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
It was added in .Net 4.5 to help with the increasingly frequent usage of async
and offloading work to the ThreadPool
.
Task.Factory.StartNew
(added with TPL in .Net 4.0) is much more robust. You should only use it if Task.Run
isn't enough, for example when you want to use TaskCreationOptions.LongRunning
(though it's unnecessary when the delegate is async. More on that on my blog: LongRunning Is Useless For Task.Run With async-await). More on Task.Factory.StartNew
in Task.Run vs Task.Factory.StartNew
Don't ever create a Task
and call Start()
unless you find an extremely good reason to do so. It should only be used if you have some part that needs to create tasks but not schedule them and another part that schedules without creating. That's almost never an appropriate solution and could be dangerous. More in "Task.Factory.StartNew" vs "new Task(...).Start"
In conclusion, mostly use Task.Run
, use Task.Factory.StartNew
if you must and never use Start
.
'Programming' 카테고리의 다른 글
SSH를 통해 Windows에서 원격 Linux 폴더를 마운트하려면 어떻게합니까? (0) | 2020.07.06 |
---|---|
RequireJS에서 단위 테스트에 대한 종속성을 어떻게 조롱 할 수 있습니까? (0) | 2020.07.06 |
ASP.NET MVC : @section의 목적은 무엇입니까? (0) | 2020.07.06 |
TDD와 BDD의 주요 차이점은 무엇입니까? (0) | 2020.07.06 |
목록 이해와 기능적 기능이 "for loop"보다 빠릅니까? (0) | 2020.07.06 |