Task.Factory.StartNew()與Task.Run()

  • 1612
  • 0
  • 2014-08-15

摘要:Task.Factory.StartNew()與Task.Run()

第一、Task.Factory.StartNew Method(Action) creates and starts a task.[1]

第二、Calling StartNew is functionally equivalent to creating a Task<TResult> using one of its constructors and then calling Start to schedule it for execution.[1]

第三、Starting with the .NET Framework 4.5, you can use the Run method with an Action object as a quick way to call StartNew with default parameters.[1]

第四、For .Net Framework 4.0, Microsoft recommends using Factory.StartNew() for simple, short-lived tasks.[2]

第五、Task.Factory.StartNew Method(Action)的優點:程式設計師可以自行決定1、設定選項。2、傳遞任意的狀態。3、啟用取消作業機制。4、控制排程行為。[3]

第六、Task.Factory.StartNew Method(Action)的缺點:過度複雜。需要時間熟悉建構函式的各個參數的使用方法。[3]

第七、解決Task.Factory.StartNew Method(Action)的缺點的對策:使用Task.Run。[3]

第八、Task.Run Method queues the specified work to run on the ThreadPool and returns a task or Task(TResult) handle for that work.[4]

第九、When you pass an Action to Task.Run:[3]

Task.Run(someAction);

that’s exactly equivalent to:

Task.Factory.StartNew(someAction, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

 

參考資料來源:

[1]TaskFactory.StartNew Method
http://msdn.microsoft.com/en-us/library/system.threading.tasks.taskfactory.startnew(v=vs.110).aspx

[2]Pro .Net 4 Parallel Programming in C#,p10
http://www.amazon.com/Parallel-Programming-Experts-Freeman-published/dp/B00E6TGGNQ/ref=sr_1_2?ie=UTF8&qid=1408066156&sr=8-2&keywords=Pro+.Net+4+Parallel+Programming+in+C%23

[3]Task.Run vs Task.Factory.StartNew
http://blogs.msdn.com/b/pfxteam/archive/2011/10/24/10229468.aspx

[4]Task.Run Method
http://msdn.microsoft.com/en-us/library/system.threading.tasks.task.run(v=vs.110).aspx