ThreadPool.SetMinThreads(Int32, Int32) 方法

定义

发出新的请求时,在切换到管理线程创建和销毁的算法之前设置线程池按需创建的线程的最小数量。

public:
 static bool SetMinThreads(int workerThreads, int completionPortThreads);
public static bool SetMinThreads (int workerThreads, int completionPortThreads);
static member SetMinThreads : int * int -> bool
Public Shared Function SetMinThreads (workerThreads As Integer, completionPortThreads As Integer) As Boolean

参数

workerThreads
Int32

要由线程池根据需要创建的新的最小工作程序线程数。

completionPortThreads
Int32

要由线程池根据需要创建的新的最小空闲异步 I/O 线程数。

返回

Boolean

如果更改成功,则为 true;否则为 false

示例

以下示例将最小工作线程数设置为 4,并为最小异步 I/O 完成线程数保留原始值。

using namespace System;
using namespace System::Threading;
int main()
{
   int minWorker;
   int minIOC;
   
   // Get the current settings.
   ThreadPool::GetMinThreads( minWorker, minIOC );
   
   // Change the minimum number of worker threads to four, but
   // keep the old setting for minimum asynchronous I/O
   // completion threads.
   if ( ThreadPool::SetMinThreads( 4, minIOC ) )
   {
      
      // The minimum number of threads was set successfully.
   }
   else
   {
      
      // The minimum number of threads was not changed.
   }
}
using System;
using System.Threading;

public class Test
{
    public static void Main()
    {
        int minWorker, minIOC;
        // Get the current settings.
        ThreadPool.GetMinThreads(out minWorker, out minIOC);
        // Change the minimum number of worker threads to four, but
        // keep the old setting for minimum asynchronous I/O 
        // completion threads.
        if (ThreadPool.SetMinThreads(4, minIOC))
        {
            // The minimum number of threads was set successfully.
        }
        else
        {
            // The minimum number of threads was not changed.
        }
    }
}
Imports System.Threading

Public Class Test

    <MTAThread> _
    Public Shared Sub Main()
        Dim minWorker, minIOC As Integer
        ' Get the current settings.
        ThreadPool.GetMinThreads(minWorker, minIOC)
        ' Change the minimum number of worker threads to four, but
        ' keep the old setting for minimum asynchronous I/O 
        ' completion threads.
        If ThreadPool.SetMinThreads(4, minIOC) Then
            ' The minimum number of threads was set successfully.
        Else
            ' The minimum number of threads was not changed.
        End If
    End Sub
End Class

注解

线程池按需提供新的工作线程或 I/O 完成线程,直到达到每个类别的最小值。 达到最小值后,线程池可以在该类别中创建其他线程,或等到某些任务完成。 从 .NET Framework 4 开始,线程池创建和销毁线程以优化吞吐量,该吞吐量定义为每个单位时间完成的任务数。 线程过少可能无法实现可用资源的最优利用,而线程过多则可能增加资源争用。

需求较低时,线程池线程的实际数量可以低于最小值。

如果指定负数或大于使用 GetMaxThreads) 获取的活动线程池 (线程的最大数目的数字, SetMinThreadsfalse 返回且不会更改任何一个最小值。

注意

默认情况下,最小线程数设置为系统上的处理器数。 可以使用该方法 SetMinThreads 增加最小线程数。 但是,不必要地增加这些值可能导致性能问题。 如果在同一时间开始太多的任务,则所有任务均可能会很慢。 在大多数情况下,线程池将使用自己的算法更好地分配线程。 将最小处理器减少到小于处理器数也会损害性能。

适用于

另请参阅