什么时候在 C# 中使用线程池? [英] When to use thread pool in C#?

查看:44
本文介绍了什么时候在 C# 中使用线程池?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试学习 C# 中的多线程编程,但我对何时最好使用线程池与创建自己的线程感到困惑.一本书建议仅将线程池用于小任务(无论这意味着什么),但我似乎找不到任何真正的指导方针.

I have been trying to learn multi-threaded programming in C# and I am confused about when it is best to use a thread pool vs. create my own threads. One book recommends using a thread pool for small tasks only (whatever that means), but I can't seem to find any real guidelines.

线程池与创建自己的线程相比有哪些优缺点?每个用例有哪些示例用例?

What are some pros and cons of thread pools vs creating my own threads? And what are some example use cases for each?

推荐答案

如果您有许多需要持续处理的逻辑任务,并且您希望这些任务并行完成,请使用池+调度程序.

If you have lots of logical tasks that require constant processing and you want that to be done in parallel use the pool+scheduler.

如果您需要并发执行与 IO 相关的任务,例如从远程服务器下载内容或访问磁盘,但需要每隔几分钟执行一次,那么请创建自己的线程并在完成后终止它们.

If you need to make your IO related tasks concurrently such as downloading stuff from remote servers or disk access, but need to do this say once every few minutes, then make your own threads and kill them once you're finished.

关于一些注意事项,我将线程池用于数据库访问、物理/模拟、AI(游戏)以及在处理大量用户定义任务的虚拟机上运行的脚本任务.

About some considerations, I use thread pools for database access, physics/simulation, AI(games), and for scripted tasks ran on virtual machines that process lots of user defined tasks.

通常一个池由每个处理器 2 个线程组成(现在很可能是 4 个),但是如果您知道需要多少线程,您可以设置所需的线程数量.

Normally a pool consists of 2 threads per processor (so likely 4 nowadays), however you can set up the amount of threads you want, if you know how many you need.

创建自己的线程的原因是上下文更改,(即线程需要交换进出进程以及它们的内存时).有无用的上下文更改,比如当你不使用你的线程时,就像人们说的那样让它们闲着,很容易使你的程序性能减半(假设你有 3 个休眠线程和 2 个活动线程).因此,如果那些下载线程只是在等待,它们会消耗大量 CPU 并为您的实际应用程序冷却缓存

The reason to make your own threads is because of context changes, (thats when threads need to swap in and out of the process, along with their memory). Having useless context changes, say when you aren't using your threads, just leaving them sit around as one might say, can easily half the performance of your program (say you have 3 sleeping threads and 2 active threads). Thus if those downloading threads are just waiting they're eating up tons of CPU and cooling down the cache for your real application

这篇关于什么时候在 C# 中使用线程池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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