c# - 控制 dotnet core 的 ThreadPool 中的线程数

标签 c# .net-core threadpool

我在我的 MacOS 上运行 dotnet 核心版本 2.1.3,我尝试使用默认线程池但没有成功。我尝试通过多种方式修改线程数(其中大部分我已经用谷歌搜索过了):

Program.cs

public static void Main(string[] args)
{
    ThreadPool.SetMinThreads(1, 1);
    ThreadPool.SetMaxThreads(1, 1);
    DoSomethingAsync();
}

.csproj

<PropertyGroup>
  <ServerGarbageCollection>true</ServerGarbageCollection>
  <ConcurrentGarbageCollection>true</ConcurrentGarbageCollection>
  <RetainVMGarbageCollection>true</RetainVMGarbageCollection>
  <ThreadPoolMinThreads>1</ThreadPoolMinThreads>
  <ThreadPoolMaxThreads>1</ThreadPoolMaxThreads>
</PropertyGroup>

环境变量

$ ComPlus_ThreadPool_ForceMinWorkerThreads=1 ComPlus_ThreadPool_ForceMaxWorkerThreads=1 dotnet run

这些似乎都没有任何效果:

$ ps -M 97046
USER           PID   TT   %CPU STAT PRI     STIME     UTIME COMMAND
XXX 97046 s002    0.0 S    31T   0:00.02   0:00.07 dotnet exec /XXX
             97046         0.0 S    31T   0:00.00   0:00.00 
             97046         0.0 S    31T   0:00.00   0:00.00 
             97046         0.0 S    31T   0:00.00   0:00.00 
             97046         0.0 S    31T   0:00.00   0:00.00 
             97046         0.0 S    31T   0:00.00   0:00.00 
             97046         0.0 S    31T   0:00.00   0:00.00 
             97046         0.0 S    31T   0:00.00   0:00.00 

我在这里错过了什么?该操作系统是特定的吗?

最佳答案

The docs状态:

You cannot set the maximum number of worker threads or I/O completion threads to a number smaller than the number of processors on the computer.

鉴于您有 8 个处理器,因此您不能将其设置为只有一个。

此外,调用:

ThreadPool.SetMaxThreads(1, 1);

不会将您的进程限制为单个线程(即使它允许您将其设置为 1,但它不会,因为 1 小于 8)。它只是限制了线程池的大小。该程序可以(并且将)仍然使用多个线程。

例如,GC 可能会在单独的线程上运行。或者您可以创建自己的独立线程(不使用线程池)。限制线程池的最大大小不会对此产生影响。

关于c# - 控制 dotnet core 的 ThreadPool 中的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49320226/

相关文章:

c# - 使用控制反转来构建与调用者的依赖关系

multithreading - 使用 Future.successful 和 Future.failed 是否从执行上下文管理的线程池中请求线程

c# - OpenHtmlToPdf 访问被 ASP.NET 拒绝

macos - 在Mac上的.NET Core中使用Nuget安装包

c# - 长期存储多个字符并恢复它们

c# - RSA 处置对象错误 - 每隔一个测试

java - 如何处理由于 WebSphere 中的多个 AJAX 请求而导致的高线程使用率

java - 如何使用 ExecutorService 递归调度任务

c# - 从 Lucene 查询中获取不同值的更快方法

c# - 仅 Entity Framework 代码错误 : the model backing the context has changed since the database was created