Exportar (0) Imprimir
Expandir todo

ThreadPool.GetMaxThreads (Método)

Actualización: noviembre 2007

Recupera el número de solicitudes al grupo de subprocesos que pueden estar activas al mismo tiempo. Todas las solicitudes que pasen de ese número permanecen en la cola hasta que haya subprocesos de grupo de subprocesos disponibles.

Espacio de nombres:  System.Threading
Ensamblado:  mscorlib (en mscorlib.dll)

public static void GetMaxThreads(
	out int workerThreads,
	out int completionPortThreads
)
public static void GetMaxThreads(
	/** @attribute OutAttribute */ /** @ref */int workerThreads,
	/** @attribute OutAttribute */ /** @ref */int completionPortThreads
)
public static function GetMaxThreads(
	workerThreads : int, 
	completionPortThreads : int
)

Parámetros

workerThreads
Tipo: System.Int32%
Número máximo de subprocesos de trabajo del grupo de subprocesos.
completionPortThreads
Tipo: System.Int32%
Número máximo de subprocesos de E/S asincrónicos del grupo de subprocesos.

Cuando se devuelve GetMaxThreads, la variable que especifica workerThreads contiene el número máximo de subprocesos de trabajo permitidos en el grupo de subprocesos, y la variable que especifica completionPortThreads contiene el número máximo de subprocesos de E/S asincrónicos permitidos en el grupo de subprocesos.

El método GetAvailableThreads se puede utilizar para determinar el número real de subprocesos del grupo de subprocesos en un momento dado.

Puede utilizar SetMaxThreads para establecer el número máximo de subprocesos de trabajo y subprocesos de E/S asincrónicos en el grupo de subprocesos.

Se pueden poner en la cola tantas solicitudes del grupo de subprocesos como permita la memoria del sistema. Si hay más solicitudes que subprocesos de grupo de subprocesos, las solicitudes adicionales permanecen en la cola hasta que hay subprocesos de grupo de subprocesos disponibles.

En el código de ejemplo siguiente se muestra la forma de recuperar un recuento del número máximo y disponible de subprocesos en el grupo de subprocesos. Se coloca en la cola un elemento de trabajo que utiliza FileStream para escribir de forma asincrónica en dos archivos. El tiempo de los métodos de devolución de llamada se calcula de forma que se superpongan. Un subproceso de trabajo calcula el elemento de trabajo y, dependiendo de la velocidad y número de procesadores del equipo, uno o dos subprocesos de puerto de finalización controlan las operaciones de escritura.

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.");
        }
    }
}


import System.*;
import System.IO.*;
import System.Security.Permissions.*;
import System.Threading.*;
import System.Threading.Thread;

// 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
{
    public static void main(String[] args)
    {
        AutoResetEvent mainEvent = new AutoResetEvent(false);
        int workerThreads = 0;
        int portThreads = 0;

        ThreadPool.GetMaxThreads(workerThreads, portThreads);
        Console.WriteLine("\nMaximum worker threads: \t{0}" + 
            "\nMaximum completion port threads: {1}",
            String.valueOf(workerThreads), String.valueOf(portThreads));
        ThreadPool.GetAvailableThreads(workerThreads, portThreads);
        Console.WriteLine("\nAvailable worker threads: \t{0}" + 
            "\nAvailable completion port threads: {1}\n", 
            String.valueOf(workerThreads), String.valueOf(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);
    } //main
} //Test

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;
        } //State
    } //State

    ThreadPoolTest()
    {
    } //ThreadPoolTest

    public static void WorkItemMethod(Object mainEvent)
    {
        Console.WriteLine("\nStarting WorkItem.\n");

        AutoResetEvent autoEvent = new AutoResetEvent(false);

        // Create some data.
        final int arraySize = 10000;
        final int bufferSize = 1000;
        ubyte byteArray[] = new ubyte[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);
        ThreadPoolTest test = new ThreadPoolTest();
        State stateInfo1 = test.new State(fileWriter1, autoEvent);
        State stateInfo2 = test.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();
    } //WorkItemMethod

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

        State stateInfo = ((State)(asyncResult.get_AsyncState()));
        int workerThreads = 0;
        int portThreads = 0;

        try {
            ThreadPool.GetAvailableThreads(workerThreads, portThreads);
            Console.WriteLine("\nAvailable worker threads: \t{0}" +
                "\nAvailable completion port threads: {1}\n",
                String.valueOf(workerThreads), String.valueOf(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.");
        }
    } //EndWriteCallback
} //ThreadPoolTest


Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile para Smartphone, Windows Mobile para Pocket PC, Xbox 360

.NET Framework y .NET Compact Framework no admiten todas las versiones de cada plataforma. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

.NET Framework

Compatible con: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 3.5, 2.0

XNA Framework

Compatible con: 2.0, 1.0

Adiciones de comunidad

AGREGAR
Mostrar:
© 2014 Microsoft