ThreadPool 与专用线程 - 何时更喜欢哪个 [英] ThreadPool vs dedicated Thread - when to prefer which

查看:31
本文介绍了ThreadPool 与专用线程 - 何时更喜欢哪个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我应该停止使用 ThreadPool 并使用专用的 Thread 代替?我想对于长时间运行的工作,最好使用专用的 Thread,因为它不会从 ThreadPool 中窃取一个.对于较短的工作,最好使用 ThreadPool,因为创建线程和线程本身会消耗大量资源.

Is there any way (apart form actual perfomance measurements which can be pretty hard to make them realistic) or rule of thumb when I should stop using the ThreadPool and use a dedicated Thread instead? I suppose for long running work it is better to use a dedicated Thread because it doesn't peramently steal one from the ThreadPool. For shorter work it is better use the the ThreadPool because creating threads and the thread itself consumes a lot of resources.

但是魔法屏障在哪里?我如何决定使用哪种方法?

But where is the magic barrier? How do I decide which approach to use?

在简单的应用程序中,它可能没有那么重要.但我正在处理一个自定义的基于 .NET 的应用程序框架,其中单个应用程序可以拥有 lot 的插件,在大多数情况下,这些插件需要异步执行一些工作.我正在考虑为插件作者引入一个何时使用哪个的策略.

In simple applications it might not matter that much. But I am dealing with a custom .NET-based application framework where a single application can have a lot of plugins which in most cases need to do some work asynchonously. And I am thinking about introducing a policy for the plugin authors when to use which.

推荐答案

将线程池线程用于短期运行的任务.

Use thread pool threads for short running tasks.

如果您需要长时间运行的任务或需要设置线程的某些属性(例如优先级、前景、区域性等),请使用线程.

Use threads if you need a long running task or need to set some properties of the thread such as priority, foreground, culture etc.

如果可能,请使用 .NET 4 中的 Task 类.默认调度程序使用线程池,但您可以提供自己的调度程序,从而精确控制任务如何映射到线程.

If possible use the Task class in .NET 4. The default scheduler uses the thread pool, but you may provide your own scheduler and thus control exactly how tasks are mapped to threads.

这篇关于ThreadPool 与专用线程 - 何时更喜欢哪个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆