当使用任务,如果线程池满/忙会发生什么? [英] When using Task what happens if the ThreadPool is full/busy?

查看:376
本文介绍了当使用任务,如果线程池满/忙会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用它使用线程池的.NET 4的任务类,如果所有线程都很忙会发生什么?

When I am using the .Net 4 Task class which uses the ThreadPool, what happens if all Threads are busy?

请问的TaskScheduler创建一个新线程并扩展线程的线程池最大数量或是否坐着等待,直到某个线程可用?

Does the TaskScheduler create a new thread and extend the ThreadPool maximum number of threads or does it sit and wait until a thread is available?

推荐答案

在线程池的最大线程数设定为1000左右的线程上的.NET4.0 32位系统。它不太旧版本的.NET。如果你有1000个线程去,说他们封锁出于某种原因,当你排队的第1001的任务,它永远不会执行。

The maximum number of threads in the ThreadPool is set to around 1000 threads on a .NET4.0 32-bit system. It's less for older versions of .NET. If you have 1000 threads going, say they're blocking for some reason, when you queue the 1001st task, it won't ever execute.

您将永远不会打到最大线程数在32位进程。请记住,每个线程至少需要1MB的内存(这是用户模式堆栈的大小),以及任何其他开销。你已经从CLR失去了大量的内存和原生的DLL加载的,所以,如果你使用多个线程,你会打一个OutOfMemoryException。

You will never hit the max thread count in a 32 bit process. Keep in mind that each thread takes at least 1MB of memory (that's the size of the user-mode stack), plus any other overhead. You already lose a lot of memory from the CLR and native DLLs loaded, so you'll hit an OutOfMemoryException before you use that many threads.

您可以通过调用的 ThreadPool.SetMaxThreads 方法。但是,如果你希望使用多个线程,你有一个的的更大的问题,您的code。我做的不是的周围建议你惹线程池配置之类的。你很可能只是恶化的表现。

You can change the number of threads the ThreadPool can use, by calling the ThreadPool.SetMaxThreads method. However, if you're expecting to use that many threads, you have a far larger problem with your code. I do NOT recommend you mess around with ThreadPool configurations like that. You'll most likely just get worse performance.

请记住与工作 ThreadPool.QueueUserWorkItem ,线程被重新使用时,他们就完成了。如果创建一个任务或排队一个线程池线程,它的可以的或的不可以的创建一个新的线程来执行你的code。如果有可用的线程已经在游泳池,它将重新使用这些而不是创建(一个昂贵的)新的线程之一。只有当你在执行任务的方法一去不复返,你应该担心运行的线程,但就像我说的,这是一个完全不同的问题,您的code。

Keep in mind with Task and ThreadPool.QueueUserWorkItem, the threads are re-used when they're done. If you create a task or queue a threadpool thread, it may or may not create a new thread to execute your code. If there are available threads already in the pool, it will re-use one of those instead of creating (an expensive) new thread. Only if the methods you're executing in the tasks never return, should you worry about running out of threads, but like I said, that's an entirely different problem with your code.

这篇关于当使用任务,如果线程池满/忙会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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