我应该取代我所有的"新的Thread"与" Task.Factory.StartNew"? [英] Should I replace all my "new Thread" with "Task.Factory.StartNew"?
问题描述
我读过有关任务之间的不同(系统任务的优点.Threading.Task)和线程
此外MSDN说:......在.NET Framework 4中,任务是编写多的首选API 。线程,异步和并行代码
Also msdn says that "...in the .NET Framework 4, tasks are the preferred API for writing multi-threaded, asynchronous, and parallel code."
现在我的程序包含从UDP接收组播数据这样的代码:
Now my program contains such code which receive multicast data from udp:
thread = new Thread(WhileTrueFunctionToReceiveDataFromUdp);
.....
thread.Start();
我有好几个这样的线程每个插座。
我是更好的替代这段代码使用任务
?
推荐答案
这取决于你在做什么 - 如果你不打算使用的任何新功能工作
和TPL,和您现有的代码工作, 。没有理由改变。
It depends on what you're doing - if you're not going to use any of the new features in Task
and the TPL, and your existing code works, there's no reason to change.
然而,工作
有许多优点 - 特别是要运行操作一个线程池线程并返回结果。
However, Task
has many advantages - especially for operations that you want to run in a thread pool thread and return a result.
另外 - 因为你使用线程每个插座,则可能需要更长的使用寿命线程。因此,如果你切换到 Task.Factory.StartNew
,你可能要指定的任务应该是的 LongRunning 否则你会风使用大量线程池线程的套接字的数据(用默认的调度)。
Also - given that you're using "threads for each socket", you likely will have longer life threads. As such, if you do switch to Task.Factory.StartNew
, you'll potentially want to specify that the tasks should be LongRunning or you'll wind up using a lot of ThreadPool threads for your socket data (with the default scheduler).
这篇关于我应该取代我所有的"新的Thread"与" Task.Factory.StartNew"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!