Should I notice a difference in using Task vs Threads in .Net 4.0?

前端 未结 5 969
暖寄归人
暖寄归人 2021-02-05 08:59

I updated my code to use Tasks instead of threads....

Looking at memory usage and CPU I do not notices any improvements on the multi-core PC, Is this expected?

M

5条回答
  •  春和景丽
    2021-02-05 09:41

    There are various implications to using Tasks instead of Threads, but performance isn't a major one (assuming you weren't creating huge numbers of threads.) A few key differences:

    1. The default TaskScheduler will use thread pooling, so some Tasks may not start until other pending Tasks have completed. If you use Thread directly, every use will start a new Thread.
    2. When an exception occurs in a Task, it gets wrapped into an AggregateException that calling code can receive when it waits for the Task to complete or if you register a continuation on the Task. This is because you can also do things like wait on multiple Tasks to complete, in which case multiple exceptions can be thrown and aggregated.
    3. If you don't observe an unhandled exception thrown by a Task, it will (well, may) eventually be thrown by the finalizer of the Task, which is particularly nasty. I always recommend hooking the TaskScheduler.UnobservedTaskException event so that you can at least log these failures before the application blows up. This is different from Thread exceptions, which show up in the AppDomain.UnhandledException event.

提交回复
热议问题