我应该注意到使用任务VS在.NET 4.0中的线程区别吗?注意到、线程、区别、任务

2023-09-07 13:46:39 作者:¤某♂某♀人

我更新了我的code使用的任务,而不是线程....

查看内存使用和CPU我不通知的多核PC上的任何改进,这是正常吗?

我的应用程序基本上是启动线程/于不同对象的任务在运行时...

我做的是一个简单的

 任务A =新的任务(...)
a.Start();
 

解决方案

有不同的影响,使用任务,而不是主题,但表现不是一个主要的(假设你没有创建线程的巨大的数字)。A几个关键的不同:

在默认的TaskScheduler会使用线程池,所以有些任务可能无法启动,直到有其他尚未完成的任务已经完成。如果你直接使用线程,每一次使用都会启动一个新的主题。 在当前异常的任务时,它被包裹成一个AggregateException,调用code可当等待任务完成接收或如果你注册一个延续的任务。这是因为,你还可以做的事情一样等待多个任务来完成,在这种情况下,多个异常可以被抛出和汇总。 如果您不遵守未处理的异常抛出一个任务,它会(当然,可能)最终被抛出的的任务的,这是特别讨厌的终结。我总是建议挂钩TaskScheduler.UnobservedTaskException事件,这样你至少可以登录这些故障之前,应用程序炸毁。这是自Thread例外,这显示在AppDomain.UnhandledException事件不同。 狗年这几个生肖容易招财进宝,财运滚滚,但在工作中需要注意几点

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?

My application essentially starts up threads/tasks in different objects when it runs...

All I'm doing is a simple

Task a = new Task(...)
a.Start();

解决方案

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:

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. 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. 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.