c# - 每次执行 N 个线程的最佳实践是什么?

标签 c# .net multithreading

我有很多线程,如果我让 .NET 运行时决定同时运行多少线程,它通常会触发 OutOfMemoryException,因为操作非常繁重。

每次请求到达我的服务器时,我都需要运行一个线程。我想做一个 ThreadPool.EnqueueWorkItem 但是说:请不要在给定时间运行超过 2 个。等待其中一个完成,然后再开始下一个。

这种情况下的最佳做法是什么。

最佳答案

使用 ThreadPool.SetMaxThreads 方法。

来自 MSDN:

Sets the number of requests to the thread pool that can be active concurrently. All requests above that number remain queued until thread pool threads become available.

重要说明:

If the common language runtime is hosted, for example by Internet Information Services (IIS) or SQL Server, the host can limit or prevent changes to the thread pool size. Use caution when changing the maximum number of threads in the thread pool. While your code might benefit, the changes might have an adverse effect on code libraries you use. Setting the thread pool size too large can cause performance problems. If too many threads are executing at the same time, the task switching overhead becomes a significant factor.

此外,因为您提到了 OutOfMemoryException,请尝试释放未使用的资源(例如调用 Dispose() 如果可用)。

更新:

正如@erikH 评论的那样,重要 需要注意的是,此功能将限制整个线程池,但如果是较大应用程序的一部分,当某些繁重的任务时,这也会限制所有快速任务需要所有可用的线程池线程。

关于c# - 每次执行 N 个线程的最佳实践是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24145003/

相关文章:

.net - 我应该使用什么?覆盖还是重载?

c# - 使用 for 循环 C# 制作动画的多个图像

c# - 不能直接从 "this"对象使用固定大小的缓冲区

.net - vb.net 按顺序停靠两个控件

c# - 如何从数据绑定(bind)组合框中隐藏所选项目(Datagridviewcombobox)

java - 为什么我在更新 TextView 时得到 Resources$NotFoundException?

c# - TCP Accept 循环的线程类型 : BackgroundWorker, Thread,或 ThreadPool

c - 使用共享内存(mmap)和信号量进行进程间通信

c# - 将现有代码库移植到不同的芯片组

c# - 按字符串值获取类