Export (0) Print
Expand All
This topic has not yet been rated - Rate this topic

ThreadPool.GetMaxThreads Method

Retrieves 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.

[Visual Basic]
Public Shared Sub GetMaxThreads( _
   <Out()> ByRef workerThreads As Integer, _
   <Out()> ByRef completionPortThreads As Integer _
)
[C#]
public static void GetMaxThreads(
   out int workerThreads,
   out int completionPortThreads
);
[C++]
public: static void GetMaxThreads(
   [
   Out
] int* workerThreads,
   [
   Out
] int* completionPortThreads
);
[JScript]
public static function GetMaxThreads(
   workerThreads : int,
 completionPortThreads : int
);

Parameters

workerThreads
The maximum number of worker threads in the thread pool.
completionPortThreads
The maximum number of asynchronous I/O threads in the thread pool.

Remarks

When GetMaxThreads returns, the variable specified by workerThreads contains the maximum number of worker threads allowed in the thread pool, and the variable specified by completionPortThreads contains the maximum number of asynchronous I/O threads allowed in the thread pool.

You can use GetAvailableThreads to determine the actual number of threads in the thread pool at any given time.

You can queue as many thread pool requests as system memory allows. If there are more requests than thread pool threads, the additional requests remain queued until thread pool threads become available.

Example

[Visual Basic, C#, C++] The following code example shows how to retrieve a count of the maximum and available number of threads in the thread pool. A work item is queued that uses FileStream to asynchronously write to two files. The callback methods are timed to overlap. A worker thread handles the work item and, depending on the speed and number of processors on the computer, one or two completion port threads handle the write operations.

[Visual Basic] 
Imports Microsoft.VisualBasic
Imports System
Imports System.IO
Imports System.Security.Permissions
Imports System.Threading

' Request permission to create two data files.
<Assembly: FileIOPermissionAttribute(SecurityAction.RequestMinimum, _
    All := "C:\Test1111.dat")>
<Assembly: FileIOPermissionAttribute(SecurityAction.RequestMinimum, _
    All := "C:\Test2222.dat")>

Public Class Test

    Shared Sub Main()
        Dim mainEvent As New AutoResetEvent(False)
        Dim workerThreads As Integer 
        Dim portThreads As Integer 

        ThreadPool.GetMaxThreads(workerThreads, portThreads)
        Console.WriteLine(vbCrLf & "Maximum worker threads: " & _
            vbTab & "{0}" & vbCrLf & "Maximum completion port " & _
            "threads: {1}", workerThreads, portThreads)

        ThreadPool.GetAvailableThreads(workerThreads, portThreads)
        Console.WriteLine(vbCrLf & "Available worker threads: " & _
            vbTab & "{0}" & vbCrLf & "Available completion port " & _
            "threads: {1}" & vbCrLf, workerThreads, portThreads)

        ThreadPool.QueueUserWorkItem(AddressOf _
            ThreadPoolTest.WorkItemMethod, mainEvent)
           
        ' Since ThreadPool threads are background threads, 
        ' wait for the work item to signal before ending Main.
        mainEvent.WaitOne(5000, False)
    End Sub

End Class

Public Class ThreadPoolTest

    ' Maintains state information to be passed to EndWriteCallback.
    ' This information allows the callback to end the asynchronous
    ' write operation and signal when it is finished.
    Class State
        Public fStream As FileStream
        Public autoEvent As AutoResetEvent

        Public Sub New(aFileStream As FileStream, anEvent As AutoResetEvent)
            fStream   = aFileStream
            autoEvent = anEvent
        End Sub
    End Class   
    
    Private Sub New
    End Sub

    Shared Sub WorkItemMethod(mainEvent As Object)
    
        Console.WriteLine(vbCrLf & "Starting WorkItem." & vbCrLf)
        Dim autoEvent As New AutoResetEvent(False)

        ' Create some data.
        Const ArraySize As Integer  = 10000
        Const BufferSize As Integer =  1000
        Dim byteArray As Byte() = New Byte(ArraySize){}
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(byteArray)

        ' Create two files and two State objects. 
        Dim fileWriter1 As FileStream = _
            New FileStream("C:\Test1111.dat", FileMode.Create, _
            FileAccess.ReadWrite, FileShare.ReadWrite, _
            BufferSize, True)
        Dim fileWriter2 As FileStream = _
            New FileStream("C:\Test2222.dat", FileMode.Create, _
            FileAccess.ReadWrite, FileShare.ReadWrite, _
            BufferSize, True)
        Dim stateInfo1 As New State(fileWriter1, autoEvent)
        Dim stateInfo2 As New State(fileWriter2, autoEvent)

        ' Asynchronously write to the files.
        fileWriter1.BeginWrite(byteArray, 0, byteArray.Length, _
            AddressOf EndWriteCallback, stateInfo1)
        fileWriter2.BeginWrite(byteArray, 0, byteArray.Length, _
            AddressOf EndWriteCallback, stateInfo2)

        ' Wait for the callbacks to signal.
        autoEvent.WaitOne()
        autoEvent.WaitOne()

        fileWriter1.Close()
        fileWriter2.Close()
        Console.WriteLine(vbCrLf & "Ending WorkItem." & vbCrLf)

        ' Signal Main that the work item is finished.
        DirectCast(mainEvent, AutoResetEvent).Set()
    
    End Sub

    Shared Sub EndWriteCallback(asyncResult As IAsyncResult)
    
        Console.WriteLine("Starting EndWriteCallback.")

        Dim stateInfo As State = _
            DirectCast(asyncResult.AsyncState, State)
        Dim workerThreads As Integer 
        Dim portThreads As Integer 
        Try
            ThreadPool.GetAvailableThreads(workerThreads, portThreads)
            Console.WriteLine(vbCrLf & "Available worker " & _
                "threads:" & vbTab & "{0}" & vbCrLf & "Available " & _
                "completion port threads: {1}" & vbCrLf, _
                workerThreads, portThreads)

            stateInfo.fStream.EndWrite(asyncResult)

            ' Sleep so the other thread has a chance to run
            ' before the current thread ends.
            Thread.Sleep(1500)
        Finally
        
            ' Signal that the current thread is finished.
            stateInfo.autoEvent.Set()
            Console.WriteLine("Ending EndWriteCallback.")
        End Try
    
    End Sub
End Class

[C#] 
using System;
using System.IO;
using System.Security.Permissions;
using System.Threading;

// Request permission to create two data files.
[assembly: FileIOPermissionAttribute(SecurityAction.RequestMinimum, 
    All = @"C:\Test1@##.dat")]
[assembly: FileIOPermissionAttribute(SecurityAction.RequestMinimum, 
    All = @"C:\Test2@##.dat")]

class Test
{
    static void Main()
    {
        AutoResetEvent mainEvent = new AutoResetEvent(false);
        int workerThreads;
        int portThreads;

        ThreadPool.GetMaxThreads(out workerThreads, out portThreads);
        Console.WriteLine("\nMaximum worker threads: \t{0}" +
            "\nMaximum completion port threads: {1}",
            workerThreads, portThreads);

        ThreadPool.GetAvailableThreads(out workerThreads, 
            out portThreads);
        Console.WriteLine("\nAvailable worker threads: \t{0}" +
            "\nAvailable completion port threads: {1}\n",
            workerThreads, portThreads);

        ThreadPool.QueueUserWorkItem(new 
            WaitCallback(ThreadPoolTest.WorkItemMethod), mainEvent);
           
        // Since ThreadPool threads are background threads, 
        // wait for the work item to signal before ending Main.
        mainEvent.WaitOne(5000, false);
    }
}

class ThreadPoolTest
{
    // Maintains state information to be passed to EndWriteCallback.
    // This information allows the callback to end the asynchronous
    // write operation and signal when it is finished.
    class State
    {
        public FileStream     fStream;
        public AutoResetEvent autoEvent;

        public State(FileStream fStream, AutoResetEvent autoEvent)
        {
            this.fStream   = fStream;
            this.autoEvent = autoEvent;
        }
    }

    ThreadPoolTest() {}

    public static void WorkItemMethod(object mainEvent)
    {
        Console.WriteLine("\nStarting WorkItem.\n");
        AutoResetEvent autoEvent = new AutoResetEvent(false);

        // Create some data.
        const int ArraySize  = 10000;
        const int BufferSize =  1000;
        byte[] byteArray = new Byte[ArraySize];
        new Random().NextBytes(byteArray);

        // Create two files and two State objects. 
        FileStream fileWriter1 = 
            new FileStream(@"C:\Test1@##.dat", FileMode.Create, 
            FileAccess.ReadWrite, FileShare.ReadWrite, 
            BufferSize, true);
        FileStream fileWriter2 = 
            new FileStream(@"C:\Test2@##.dat", FileMode.Create, 
            FileAccess.ReadWrite, FileShare.ReadWrite, 
            BufferSize, true);
        State stateInfo1 = new State(fileWriter1, autoEvent);
        State stateInfo2 = new State(fileWriter2, autoEvent);

        // Asynchronously write to the files.
        fileWriter1.BeginWrite(byteArray, 0, byteArray.Length, 
            new AsyncCallback(EndWriteCallback), stateInfo1);
        fileWriter2.BeginWrite(byteArray, 0, byteArray.Length, 
            new AsyncCallback(EndWriteCallback), stateInfo2);

        // Wait for the callbacks to signal.
        autoEvent.WaitOne();
        autoEvent.WaitOne();

        fileWriter1.Close();
        fileWriter2.Close();
        Console.WriteLine("\nEnding WorkItem.\n");

        // Signal Main that the work item is finished.
        ((AutoResetEvent)mainEvent).Set();
    }

    static void EndWriteCallback(IAsyncResult asyncResult)
    {
        Console.WriteLine("Starting EndWriteCallback.");

        State stateInfo = (State)asyncResult.AsyncState;
        int workerThreads;
        int portThreads;
        try
        {
            ThreadPool.GetAvailableThreads(out workerThreads, 
                out portThreads);
            Console.WriteLine("\nAvailable worker threads: \t{0}" +
                "\nAvailable completion port threads: {1}\n",
                workerThreads, portThreads);

            stateInfo.fStream.EndWrite(asyncResult);

            // Sleep so the other thread has a chance to run
            // before the current thread ends.
            Thread.Sleep(1500);
        }
        finally
        {
            // Signal that the current thread is finished.
            stateInfo.autoEvent.Set();
            Console.WriteLine("Ending EndWriteCallback.");
        }
    }
}

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::IO;
using namespace System::Security::Permissions;
using namespace System::Threading;

// Request permission to create two data files.
[assembly: FileIOPermissionAttribute(SecurityAction::RequestMinimum, 
    All = "C:\\Test1#@@.dat")];
[assembly: FileIOPermissionAttribute(SecurityAction::RequestMinimum, 
    All = "C:\\Test2#@@.dat")];

__gc class ThreadPoolTest
{
    // Maintains state information to be passed to EndWriteCallback.
    // This information allows the callback to end the asynchronous
    // write operation and signal when it is finished.
    __gc class State
    {
    public:
        FileStream*     fStream;
        AutoResetEvent* autoEvent;

        State(FileStream* fStream, AutoResetEvent* autoEvent)
        {
            this->fStream   = fStream;
            this->autoEvent = autoEvent;
        }
    };

    ThreadPoolTest() {}

    static void EndWriteCallback(IAsyncResult* asyncResult)
    {
        Console::WriteLine(S"Starting EndWriteCallback.");

        State* stateInfo = 
            dynamic_cast<State*>(asyncResult->AsyncState);
        int workerThreads;
        int portThreads;
        try
        {
            ThreadPool::GetAvailableThreads(&workerThreads, 
                &portThreads);
            Console::WriteLine(S"\nAvailable worker threads: \t{0}" 
                S"\nAvailable completion port threads: {1}\n",
                workerThreads.ToString(), portThreads.ToString());

            stateInfo->fStream->EndWrite(asyncResult);

            // Sleep so the other thread has a chance to run
            // before the current thread ends.
            Thread::Sleep(1500);
        }
        catch(Exception* e)
        {
        }
        __finally
        {
            // Signal that the current thread is finished.
            stateInfo->autoEvent->Set();
            Console::WriteLine(S"Ending EndWriteCallback.");
        }
    }

public:
    static void WorkItemMethod(Object* mainEvent)
    {
        Console::WriteLine(S"\nStarting WorkItem.\n");
        AutoResetEvent* autoEvent = new AutoResetEvent(false);

        // Create some data.
        const int ArraySize  = 10000;
        const int BufferSize =  1000;
        Byte byteArray[] = new Byte[ArraySize];
        (new Random())->NextBytes(byteArray);

        // Create two files and two State objects. 
        FileStream* fileWriter1 = 
            new FileStream("C:\\Test1@##.dat", FileMode::Create, 
            FileAccess::ReadWrite, FileShare::ReadWrite, 
            BufferSize, true);
        FileStream* fileWriter2 = 
            new FileStream("C:\\Test2@##.dat", FileMode::Create, 
            FileAccess::ReadWrite, FileShare::ReadWrite, 
            BufferSize, true);
        State* stateInfo1 = new State(fileWriter1, autoEvent);
        State* stateInfo2 = new State(fileWriter2, autoEvent);

        // Asynchronously write to the files.
        fileWriter1->BeginWrite(byteArray, 0, byteArray->Length, 
            new AsyncCallback(0, &ThreadPoolTest::EndWriteCallback),
            stateInfo1);
        fileWriter2->BeginWrite(byteArray, 0, byteArray->Length, 
            new AsyncCallback(0, &ThreadPoolTest::EndWriteCallback),
            stateInfo2);

        // Wait for each callback to finish.
        autoEvent->WaitOne();
        autoEvent->WaitOne();

        fileWriter1->Close();
        fileWriter2->Close();
        Console::WriteLine(S"\nEnding WorkItem.\n");

        // Signal Main that the work item is finished.
        dynamic_cast<AutoResetEvent*>(mainEvent)->Set();
    }
};

void main()
{
    AutoResetEvent* mainEvent = new AutoResetEvent(false);
    int workerThreads;
    int portThreads;

    ThreadPool::GetMaxThreads(&workerThreads, &portThreads);
    Console::WriteLine(S"\nMaximum worker threads: \t{0}" 
        S"\nMaximum completion port threads: {1}",
        workerThreads.ToString(), portThreads.ToString());

    ThreadPool::GetAvailableThreads(&workerThreads, &portThreads);
    Console::WriteLine(S"\nAvailable worker threads: \t{0}" 
        S"\nAvailable completion port threads: {1}\n",
        workerThreads.ToString(), portThreads.ToString());

    ThreadPool::QueueUserWorkItem(new WaitCallback(0, 
        &ThreadPoolTest::WorkItemMethod), mainEvent);

    // Since ThreadPool threads are background threads, 
    // wait for the work item to signal before ending main().
    mainEvent->WaitOne(5000, false);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

ThreadPool Class | ThreadPool Members | System.Threading Namespace | SetMinThreads | GetMinThreads | GetAvailableThreads

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.