何时使用线程池在C#? [英] When to use thread pool in C#?

查看:144
本文介绍了何时使用线程池在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 considerations you use when making this programming decision?

推荐答案

如果你有很多需要不断处理逻辑任务,你想,要在并行使用进行池+调度。

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.

编辑:关于一些注意事项,我使用线程池的数据库访问,物理/仿真,人工智能(游戏),以及脚本任务运行上处理大量的用户定义的任务虚拟机

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.

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

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天全站免登陆