Should I replace my entire "new theme" with "Task.Factory.StartNew"?

I read about the benefits of tasks. The difference between Task (System.Threading.Task) and Thread

Msdn also says that "... in the .NET Framework 4, tasks are the preferred API for writing multi-threaded, asynchronous, and parallel code."

Now my program contains code that accepts multicast data from udp:

thread = new Thread(WhileTrueFunctionToReceiveDataFromUdp); ..... thread.Start(); 

I have several such threads for each socket. Can I replace this code with Task ?

+4
source share
2 answers

It depends on what you are doing - if you are not going to use any new functions in Task and TPL, and your existing code is working, there is no reason to change.

However, Task has many advantages - especially for operations that you want to run on a thread in a thread pool and return a result.

Also, given that you use "threads for each socket", you are likely to have more life threads. Thus, if you switch to Task.Factory.StartNew , you may want to indicate that the tasks should be LongRunning or you will complete using many ThreadPool threads for your socket data (with the default scheduler).

+2
source

Do not modify anything in code that already works and will work (at least according to Microsoft). Change it only for the following reasons:

  • Do you want to use the new features offered by Tasks

  • Personal research.

Remember that at the OS level, they basically fall into the same kernel objects of the kernel.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1401690/


All Articles