Sugerir traducción
 
Otros han sugerido:

progress indicator
No hay más sugerencias.
Califique este contenido
Contraer todo/Expandir todo Contraer todo
Ver contenido:  en paraleloVer contenido: en paralelo
.NET Framework Class Library
ThreadPool Class

Updated: October 2010

Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.

System..::.Object
  System.Threading..::.ThreadPool

Namespace:  System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Visual Basic
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
    ExternalThreading := True)> _
Public NotInheritable Class ThreadPool
C#
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public static class ThreadPool
Visual C++
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public ref class ThreadPool abstract sealed
F#
[<AbstractClass>]
[<Sealed>]
[<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    ExternalThreading = true)>]
type ThreadPool =  class end

The ThreadPool type exposes the following members.

  NameDescription
Public methodStatic memberBindHandle(IntPtr) Obsolete. Binds an operating system handle to the ThreadPool.
Public methodStatic memberBindHandle(SafeHandle)Binds an operating system handle to the ThreadPool.
Public methodStatic memberGetAvailableThreadsRetrieves the difference between the maximum number of thread pool threads returned by the GetMaxThreads method, and the number currently active.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryGetMaxThreadsRetrieves 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.
Public methodStatic memberGetMinThreadsRetrieves the minimum number of threads the thread pool creates on demand, as new requests are made, before switching to an algorithm for managing thread creation and destruction.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryQueueUserWorkItem(WaitCallback)Queues a method for execution. The method executes when a thread pool thread becomes available.
Public methodStatic memberSupported by the XNA FrameworkSupported by Portable Class LibraryQueueUserWorkItem(WaitCallback, Object)Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.
Public methodStatic memberRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)Registers a delegate to wait for a WaitHandle, specifying a 32-bit signed integer for the time-out in milliseconds.
Public methodStatic memberRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)Registers a delegate to wait for a WaitHandle, specifying a 64-bit signed integer for the time-out in milliseconds.
Public methodStatic memberRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)Registers a delegate to wait for a WaitHandle, specifying a TimeSpan value for the time-out.
Public methodStatic memberRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)Registers a delegate to wait for a WaitHandle, specifying a 32-bit unsigned integer for the time-out in milliseconds.
Public methodStatic memberSupported by the XNA FrameworkSetMaxThreadsSets 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.
Public methodStatic memberSetMinThreadsSets the minimum number of threads the thread pool creates on demand, as new requests are made, before switching to an algorithm for managing thread creation and destruction.
Public methodStatic memberUnsafeQueueNativeOverlappedQueues an overlapped I/O operation for execution.
Public methodStatic memberUnsafeQueueUserWorkItemQueues the specified delegate to the thread pool, but does not propagate the calling stack to the worker thread.
Public methodStatic memberUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)Registers a delegate to wait for a WaitHandle, using a 32-bit signed integer for the time-out in milliseconds. This method does not propagate the calling stack to the worker thread.
Public methodStatic memberUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)Registers a delegate to wait for a WaitHandle, specifying a 64-bit signed integer for the time-out in milliseconds. This method does not propagate the calling stack to the worker thread.
Public methodStatic memberUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)Registers a delegate to wait for a WaitHandle, specifying a TimeSpan value for the time-out. This method does not propagate the calling stack to the worker thread.
Public methodStatic memberUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)Registers a delegate to wait for a WaitHandle, specifying a 32-bit unsigned integer for the time-out in milliseconds. This method does not propagate the calling stack to the worker thread.
Top

Many applications create threads that spend a great deal of time in the sleeping state, waiting for an event to occur. Other threads might enter a sleeping state only to be awakened periodically to poll for a change or update status information. The thread pool enables you to use threads more efficiently by providing your application with a pool of worker threads that are managed by the system. Examples of operations that use thread pool threads include the following:

  • When you create a Task or Task<(Of <(TResult>)>) object to perform some task asynchronously, by default the task is scheduled to run on a thread pool thread.

  • Asynchronous timers use the thread pool. Thread pool threads execute callbacks from the System.Threading..::.Timer class and raise events from the System.Timers..::.Timer class.

  • When you use registered wait handles, a system thread monitors the status of the wait handles. When a wait operation completes, a worker thread from the thread pool executes the corresponding callback function.

NoteNote

The threads in the managed thread pool are background threads. That is, their IsBackground properties are true. This means that a ThreadPool thread will not keep an application running after all foreground threads have exited.

You can also queue work items that are not related to a wait operation to the thread pool. To request that a work item be handled by a thread in the thread pool, call the QueueUserWorkItem method. This method takes as a parameter a reference to the method or delegate that will be called by the thread selected from the thread pool. There is no way to cancel a work item after it has been queued.

Timer-queue timers and registered wait operations also use the thread pool. Their callback functions are queued to the thread pool.

There is one thread pool per process. Beginning with the .NET Framework version 4, the default size of the thread pool for a process depends on several factors, such as the size of the virtual address space. A process can call the GetMaxThreads method to determine the number of threads. The number of threads in the thread pool can be changed by using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.

NoteNote

Unmanaged code that hosts the .NET Framework can change the size of the thread pool by using the CorSetMaxThreads function, defined in the mscoree.h file.

The thread pool provides new worker threads or I/O completion threads on demand until it reaches the minimum for each category. When a minimum is reached, the thread pool can create additional threads in that category or wait until some tasks complete. Beginning with the .NET Framework 4, the thread pool creates and destroys worker threads in order to optimize throughput, which is defined as the number of tasks that complete per unit of time. Too few threads might not make optimal use of available resources, whereas too many threads could increase resource contention.

NoteNote

When demand is low, the actual number of thread pool threads can fall below the minimum values.

You can use the GetMinThreads method to obtain these minimum values.

Caution noteCaution

You can use the SetMinThreads method to increase the minimum number of threads. However, unnecessarily increasing these values can cause performance problems. If too many tasks start at the same time, all of them might appear to be slow. In most cases the thread pool will perform better with its own algorithm for allocating threads.

When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, data that is placed in thread local storage by one method can be exposed to any other method that is executed by the same thread pool thread. A method that accesses a field that is marked with the ThreadStaticAttribute attribute could encounter different data depending on which thread pool thread executes it.

NoteNote

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

Visual Basic
Imports System
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Queue the task.
        ThreadPool.QueueUserWorkItem( _
            New WaitCallback(AddressOf ThreadProc) _
            )
        ' Note that you do not have to create the WaitCallback delegate
        ' explicitly in Visual Basic.  The following line also queues 
        ' the task:
        'ThreadPool.QueueUserWorkItem(AddressOf ThreadProc)

        Console.WriteLine("Main thread does some work, then sleeps.")
        ' If you comment out the Sleep, the main thread exits before
        ' the thread pool task runs.  The thread pool uses background
        ' threads, which do not keep the application running.  (This
        ' is a simple example of a race condition.)
        Thread.Sleep(1000)

        Console.WriteLine("Main thread exits.")
    End Sub

    ' This thread procedure performs the task.
    Shared Sub ThreadProc(stateInfo As Object)
        ' No state object was passed to QueueUserWorkItem, so 
        ' stateInfo is null.
        Console.WriteLine("Hello from the thread pool.")
    End Sub
End Class
C#
using System;
using System.Threading;
public class Example {
    public static void Main() {
        // Queue the task.
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

        Console.WriteLine("Main thread does some work, then sleeps.");
        // If you comment out the Sleep, the main thread exits before
        // the thread pool task runs.  The thread pool uses background
        // threads, which do not keep the application running.  (This
        // is a simple example of a race condition.)
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) {
        // No state object was passed to QueueUserWorkItem, so 
        // stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}
Visual C++
using namespace System;
using namespace System::Threading;
ref class Example
{
public:

   // This thread procedure performs the task.
   static void ThreadProc( Object^ stateInfo )
   {

      // No state object was passed to QueueUserWorkItem, so 
      // stateInfo is 0.
      Console::WriteLine( "Hello from the thread pool." );
   }

};

int main()
{

   // Queue the task.
   ThreadPool::QueueUserWorkItem( gcnew WaitCallback( Example::ThreadProc ) );
   Console::WriteLine( "Main thread does some work, then sleeps." );

   // If you comment out the Sleep, the main thread exits before
   // the thread pool task runs.  The thread pool uses background
   // threads, which do not keep the application running.  (This
   // is a simple example of a race condition.)
   Thread::Sleep( 1000 );
   Console::WriteLine( "Main thread exits." );
   return 0;
}

.NET Framework

Supported in: 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role not supported), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

This type is thread safe.

Date

History

Reason

October 2010

Corrected outdated default size and outdated information about the creation of new threads.

Content bug fix.

Biblioteca de clases de .NET Framework
ThreadPool (Clase)

Proporciona un grupo de subprocesos que pueden utilizarse para ejecutar tareas, exponer elementos de trabajo, procesar la E/S asincrónica, esperar en nombre de otros subprocesos y procesar temporizadores.

System..::.Object
  System.Threading..::.ThreadPool

Espacio de nombres:  System.Threading
Ensamblado:  mscorlib (en mscorlib.dll)
Visual Basic
<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization := True,  _
    ExternalThreading := True)> _
Public NotInheritable Class ThreadPool
C#
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public static class ThreadPool
Visual C++
[HostProtectionAttribute(SecurityAction::LinkDemand, Synchronization = true, 
    ExternalThreading = true)]
public ref class ThreadPool abstract sealed
F#
[<AbstractClass>]
[<Sealed>]
[<HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
    ExternalThreading = true)>]
type ThreadPool =  class end

El tipo ThreadPool expone los siguientes miembros.

  NombreDescripción
Método públicoMiembro estáticoBindHandle(IntPtr) Obsoleto. Enlaza un identificador del sistema operativo a ThreadPool.
Método públicoMiembro estáticoBindHandle(SafeHandle)Enlaza un identificador del sistema operativo a ThreadPool.
Método públicoMiembro estáticoGetAvailableThreadsRecupera la diferencia entre el número máximo de subprocesos de grupo de subprocesos devuelto por el método GetMaxThreads y el número activo actualmente.
Método públicoMiembro estáticoCompatible con XNA Frameworky5htx827.PortableClassLibrary(es-es,VS.100).gifGetMaxThreadsRecupera 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.
Método públicoMiembro estáticoGetMinThreadsRecupera el número mínimo de subprocesos que el grupo de subprocesos crea a petición, según se realizan nuevas solicitudes, antes de la conmutación a un algoritmo para administrar la creación y destrucción de subprocesos.
Método públicoMiembro estáticoCompatible con XNA Frameworky5htx827.PortableClassLibrary(es-es,VS.100).gifQueueUserWorkItem(WaitCallback)Pone en cola un método para su ejecución. El método se ejecuta cuando hay un subproceso de grupo de subprocesos disponible.
Método públicoMiembro estáticoCompatible con XNA Frameworky5htx827.PortableClassLibrary(es-es,VS.100).gifQueueUserWorkItem(WaitCallback, Object)Pone un método en cola para su ejecución y especifica un objeto que contiene los datos que debe utilizar el método. El método se ejecuta cuando hay un subproceso de grupo de subprocesos disponible.
Método públicoMiembro estáticoRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, especificando un entero de 32 bits con signo para representar el tiempo de espera en milisegundos.
Método públicoMiembro estáticoRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, especificando un entero de 64 bits con signo para representar el tiempo de espera en milisegundos.
Método públicoMiembro estáticoRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, especificando un valor de TimeSpan para el tiempo de espera.
Método públicoMiembro estáticoRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, especificando un entero de 32 bits sin signo para representar el tiempo de espera en milisegundos.
Método públicoMiembro estáticoCompatible con XNA FrameworkSetMaxThreadsEstablece 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.
Método públicoMiembro estáticoSetMinThreadsEstablece el número mínimo de subprocesos que el grupo de subprocesos crea a petición, según se realizan nuevas solicitudes, antes de la conmutación a un algoritmo para administrar la creación y destrucción de subprocesos.
Método públicoMiembro estáticoUnsafeQueueNativeOverlappedPone en cola una operación de E/S superpuesta para que se ejecute.
Método públicoMiembro estáticoUnsafeQueueUserWorkItemPone en cola el delegado especificado en el grupo de subprocesos, pero no propaga la pila de llamadas al subproceso de trabajo.
Método públicoMiembro estáticoUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int32, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, utilizando un entero de 32 bits con signo para representar el tiempo de espera en milisegundos. Este método no propaga la pila de llamadas al subproceso de trabajo.
Método públicoMiembro estáticoUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, Int64, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, especificando un entero de 64 bits con signo para representar el tiempo de espera en milisegundos. Este método no propaga la pila de llamadas al subproceso de trabajo.
Método públicoMiembro estáticoUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, TimeSpan, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, especificando un valor de TimeSpan para el tiempo de espera. Este método no propaga la pila de llamadas al subproceso de trabajo.
Método públicoMiembro estáticoUnsafeRegisterWaitForSingleObject(WaitHandle, WaitOrTimerCallback, Object, UInt32, Boolean)Registra un delegado que va a esperar a una clase WaitHandle, especificando un entero de 32 bits sin signo para representar el tiempo de espera en milisegundos. Este método no propaga la pila de llamadas al subproceso de trabajo.
Arriba

Muchas aplicaciones crean subprocesos que pasan mucho tiempo en estado de inactividad, esperando a que se produzca un evento. Otros subprocesos pueden entrar en estado de inactividad y activarse periódicamente para comprobar si se ha producido algún cambio o para actualizar la información de estado. El grupo de subprocesos permite utilizar los subprocesos de forma más eficaz, ya que suministra a la aplicación un grupo de subprocesos de trabajo administrados por el sistema. Los ejemplos de operaciones que usan subprocesos de grupo de subprocesos incluyen los siguientes:

  • Al crear un objeto Task<(Of <(TResult>)>) o Task para realizar alguna tarea de forma asincrónica, de forma predeterminada la tarea se programa para ejecutarse en un subproceso del grupo de subprocesos.

  • Los temporizadores asincrónicos utilizan el grupo de subprocesos. Los subprocesos del grupo de subprocesos ejecutan devoluciones de llamada desde la clase System.Threading..::.Timer y generan eventos desde la clase System.Timers..::.Timer.

  • Al utilizar controladores de espera registrados, un subproceso del sistema supervisa el estado de los controladores de espera. Cuando una operación de espera finaliza, un subproceso de trabajo del grupo de subprocesos ejecuta la función de devolución de llamada correspondiente.

NotaNota

Los subprocesos del grupo de subprocesos administrados son los subprocesos de fondo. Es decir, sus propiedades IsBackground son true. Esto significa que un subproceso ThreadPool no hará que la aplicación se siga ejecutando cuando todos los subprocesos de primer plano hayan terminado.

También pueden colocarse en la cola del grupo de subprocesos elementos de trabajo no relacionados con una operación de espera. Para solicitar que un subproceso del grupo de subprocesos controle un elemento de trabajo, hay que llamar al método QueueUserWorkItem. Este método toma como parámetro una referencia al método o delegado al que llamará el subproceso seleccionado del grupo de subprocesos. No se puede cancelar un elemento de trabajo después de haberlo colocado en la cola.

Los temporizadores de la cola de temporizadores y las operaciones de espera registradas también utilizan el grupo de subprocesos. Sus funciones de devolución de llamada se colocan en la cola del grupo de subprocesos.

Hay un grupo de subprocesos por proceso. A partir de .NET Framework versión 4, el tamaño predeterminado del grupo de subprocesos de un proceso depende de varios factores, como el tamaño del espacio de direcciones virtuales. Un proceso puede llamar al método GetMaxThreads para determinar el número de subprocesos. El número de subprocesos del grupo de subprocesos se puede cambiar mediante el método SetMaxThreads. Cada subproceso utiliza el tamaño de pila predeterminado y se ejecuta con la prioridad predeterminada.

NotaNota

El código no administrado que hospeda .NET Framework puede cambiar el tamaño del grupo de subprocesos mediante la función CorSetMaxThreads definida en el archivo mscoree.h.

El grupo de subprocesos proporciona nuevos subprocesos de trabajo o subprocesos de finalización de E/S a petición hasta que alcanza el mínimo para cada categoría. Cuando se alcanza un valor mínimo, el grupo de subprocesos puede crear subprocesos adicionales en esa categoría o esperar hasta que se completen algunas tareas. A partir de .NET Framework 4, el grupo de subprocesos crea y destruye los subprocesos de trabajo para optimizar el rendimiento, que se define como el número de tareas completadas por unidad de tiempo. Es posible que si hay muy pocos subprocesos, no se haga un uso óptimo de los recursos disponibles, mientras que demasiados subprocesos podrían aumentar la contención de recursos.

NotaNota

Cuando la petición es baja, el número real de subprocesos del grupo de subprocesos puede situarse por debajo de los valores mínimos.

Puede usar el método GetMinThreads para obtener estos valores mínimos.

Nota de precauciónPrecaución

Puede usar el método SetMinThreads para aumentar el número mínimo de subprocesos. Sin embargo, aumentar estos valores innecesariamente puede producir problemas de rendimiento. Si se inician demasiadas tareas al mismo tiempo, puede parecer que todas se realizan con lentitud. En la mayoría de los casos, el grupo de subprocesos se comportará mejor con su propio algoritmo para asignar los subprocesos.

Cuando el grupo de subprocesos reutiliza un subproceso, no borra los datos del almacenamiento local de subprocesos ni de los campos marcados con el atributo ThreadStaticAttribute. Por consiguiente, los datos que un método guarda en el almacenamiento local de subprocesos pueden ser expuestos por cualquier otro método que se ejecute en el mismo subproceso del grupo de subprocesos. Un método que tiene acceso a un campo que se marca con el atributo ThreadStaticAttribute podría encontrar datos diferentes dependiendo de qué subproceso del grupo de subprocesos lo ejecute.

NotaNota

El atributo HostProtectionAttribute aplicado a este tipo o miembro tiene el siguiente valor de la propiedad Resources: Synchronization | ExternalThreading. El atributo HostProtectionAttribute no afecta a las aplicaciones de escritorio (que normalmente se inician haciendo doble clic en un icono, escribiendo un comando o introduciendo una dirección URL en el explorador). Para obtener más información, vea la clase HostProtectionAttribute o Programación en SQL Server y atributos de protección de host.

Visual Basic
Imports System
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Queue the task.
        ThreadPool.QueueUserWorkItem( _
            New WaitCallback(AddressOf ThreadProc) _
            )
        ' Note that you do not have to create the WaitCallback delegate
        ' explicitly in Visual Basic.  The following line also queues 
        ' the task:
        'ThreadPool.QueueUserWorkItem(AddressOf ThreadProc)

        Console.WriteLine("Main thread does some work, then sleeps.")
        ' If you comment out the Sleep, the main thread exits before
        ' the thread pool task runs.  The thread pool uses background
        ' threads, which do not keep the application running.  (This
        ' is a simple example of a race condition.)
        Thread.Sleep(1000)

        Console.WriteLine("Main thread exits.")
    End Sub

    ' This thread procedure performs the task.
    Shared Sub ThreadProc(stateInfo As Object)
        ' No state object was passed to QueueUserWorkItem, so 
        ' stateInfo is null.
        Console.WriteLine("Hello from the thread pool.")
    End Sub
End Class
C#
using System;
using System.Threading;
public class Example {
    public static void Main() {
        // Queue the task.
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

        Console.WriteLine("Main thread does some work, then sleeps.");
        // If you comment out the Sleep, the main thread exits before
        // the thread pool task runs.  The thread pool uses background
        // threads, which do not keep the application running.  (This
        // is a simple example of a race condition.)
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) {
        // No state object was passed to QueueUserWorkItem, so 
        // stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}
Visual C++
using namespace System;
using namespace System::Threading;
ref class Example
{
public:

   // This thread procedure performs the task.
   static void ThreadProc( Object^ stateInfo )
   {

      // No state object was passed to QueueUserWorkItem, so 
      // stateInfo is 0.
      Console::WriteLine( "Hello from the thread pool." );
   }

};

int main()
{

   // Queue the task.
   ThreadPool::QueueUserWorkItem( gcnew WaitCallback( Example::ThreadProc ) );
   Console::WriteLine( "Main thread does some work, then sleeps." );

   // If you comment out the Sleep, the main thread exits before
   // the thread pool task runs.  The thread pool uses background
   // threads, which do not keep the application running.  (This
   // is a simple example of a race condition.)
   Thread::Sleep( 1000 );
   Console::WriteLine( "Main thread exits." );
   return 0;
}

.NET Framework

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

.NET Framework Client Profile

Compatible con: 4, 3.5 SP1

Compatible con:

Windows 7, Windows Vista SP1 o posterior, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (no se admite Server Core), Windows Server 2008 R2 (se admite Server Core con SP1 o posterior), Windows Server 2003 SP2

.NET Framework no admite todas las versiones de todas las plataformas. Para obtener una lista de las versiones compatibles, vea Requisitos de sistema de .NET Framework.

Este tipo es seguro para la ejecución de subprocesos.

Fecha

Historial

Motivo

Octubre de 2010

Se ha corregido el tamaño predeterminado obsoleto y la información obsoleta sobre la creación de nuevos subprocesos.

Corrección de errores de contenido.

Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Temas legales | Marcas Registradas | Declaración de privacidad
Page view tracker