.NET 4 includes a new namespace, System.Threading.Tasks, which contains classes that abstract out threading functionality. Use ThreadPool in the background. A task represents the work of a unit that should be completed. The work of this unit can be run in a separate thread or a task can be started synchronously, which requires waiting for the main tuning thread. Using tasks not only gives you an abstraction layer, but also gives you a lot of control over the underlying threads. Tasks offer a lot of flexibility when it comes to scheduling the work that needs to be done. For example, you can define a continuous task – what work should be done after a task is completed. This can make the difference between a successful task and not. In addition, tasks can be arranged in a hierarchy. For example, a parent task can create a new child task. This creates a dependency so that if you cancel the parent task, its child task will also be canceled.
Nowadays, it is popular to use task execution methods, and it is high-performance, and I don't know where the task performance is.
I tested Task and Thread myself, and I feel that Task is very slow, which greatly affects performance, and the test code is as follows:
We loop through the method 1000 times, and then the method blocks for 100 milliseconds, and the test result is as follows:
Outcome:
Thread execution takes 188 milliseconds
Task execution takes 14,671 milliseconds
The speed difference between the two is 78 times!!!
Task is very slow, don't know why this is happening, is there something wrong with my test code, or what? I hope you can explain why this happens...
|