Task.Run is only available after a dotnet framework 4.5, but Task.Factory.StartNew can use more than Task.Run parameters, can do more customization. Task.Run can be considered a simplified Task.Factory.StartNew use, in addition to specifying a thread is prolonged occupation, otherwise use Task.Run.
Long-running
The biggest difference is that the two functions can be set Task.Factory.StartNew long-running thread, then the thread pool thread will not wait for the recovery
Task.Factory.StartNew(() => { Console.WriteLine("进行 线程" + Thread.CurrentThread.ManagedThreadId); }, TaskCreationOptions.LongRunning);
Thread abnormal operation
Task.Run and Task.Factory.StartNew there are not abnormal when thrown out, so it is necessary to catch exceptions.
No reaction outside the catch exceptions, such an approach does not
for (int i = 0; i < 10; i++) { try { Task.Factory.StartNew(() => { Console.WriteLine($"Task.Factory.StartNew value {i}"); int value = 2 / (i % 2); }); } catch { Console.WriteLine("Task.Factory.StartNew异常"); } Thread.Sleep(10); } for (int j = 0; j < 10; j++) { try { Task.Run(() => { Console.WriteLine($"Task.Run value {j}"); int value = 2 / (j % 2); }); } catch { Console.WriteLine("Task.Run异常"); } Thread.Sleep(10); }
Catch the exception in the thread, which is the correct wording
for (int i = 0; i < 10; i++) { Task.Factory.StartNew(() => { try { Console.WriteLine($"Task.Factory.StartNew value {i}"); int value = 2 / (i % 2); } catch { Console.WriteLine("Task.Factory.StartNew异常"); } }); Thread.Sleep(10); } for (int j = 0; j < 10; j++) { Task.Run(() => { try { Console.WriteLine($"Task.Run value {j}"); int value = 2 / (j % 2); } catch { Console.WriteLine("Task.Run异常"); } }); Thread.Sleep(10); }
Other articles thread
1. C # in await / async Chatting
2.. NET developed in parallel optimization
3. C # Task.Run and Task.Factory.StartNew difference
4. C # multithreaded parallel processing
5. C # variables in multi-threaded Research