Esta documentación está archivada y no tiene mantenimiento.

ThreadPool.QueueUserWorkItem (Método) (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.

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

public static bool QueueUserWorkItem (
	WaitCallback callBack,
	Object state
)
public static boolean QueueUserWorkItem (
	WaitCallback callBack, 
	Object state
)
public static function QueueUserWorkItem (
	callBack : WaitCallback, 
	state : Object
) : boolean
No aplicable.

Parámetros

callBack

WaitCallback que representa el método que se va a ejecutar.

state

Objeto que contiene los datos que va a utilizar el método.

Valor devuelto

true si el método se pone en la cola correctamente; se produce la excepción OutOfMemoryException si no se puede poner en la cola el elemento de trabajo.

Tipo de excepciónCondición

ApplicationException

Se ha encontrado una condición de falta de memoria.

OutOfMemoryException

No se pudo poner en la cola el elemento de trabajo.

ArgumentNullException

callBack es referencia null (Nothing en Visual Basic).

Si el método de devolución de llamada requiere datos complejos, se puede definir una clase que los contenga.

NotaNota:

Los usuarios de Visual Basic pueden omitir el constructor WaitCallback y utilizar simplemente el operador AddressOf al pasar el método de devolución de llamadas a QueueUserWorkItem. Visual Basic llama automáticamente al constructor del delegado correcto.

Información de versión

En la versión 2.0 de .NET Framework, el valor de la propiedad Thread.CurrentPrincipal se difunde a los subprocesos de trabajo almacenados en la cola utilizando el método QueueUserWorkItem. En las versiones anteriores, la información principal no se difunde.

// This example shows how to create an object containing task
// information, and pass that object to a task queued for
// execution by the thread pool.
using System;
using System.Threading;

// TaskInfo holds state information for a task that will be
// executed by a ThreadPool thread.
public class TaskInfo {
    // State information for the task.  These members
    // can be implemented as read-only properties, read/write
    // properties with validation, and so on, as required.
    public string Boilerplate;
    public int Value;

    // Public constructor provides an easy way to supply all
    // the information needed for the task.
    public TaskInfo(string text, int number) {
        Boilerplate = text;
        Value = number;
    }
}

public class Example {
    public static void Main() {
        // Create an object containing the information needed
        // for the task.
        TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);

        // Queue the task and data.
        if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) {    
            Console.WriteLine("Main thread does some work, then sleeps.");

            // If you comment out the Sleep, the main thread exits before
            // the ThreadPool task has a chance to run.  ThreadPool 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.");
        }
        else {
            Console.WriteLine("Unable to queue ThreadPool request."); 
        }
    }

    // The thread procedure performs the independent task, in this case
    // formatting and printing a very simple report.
    //
    static void ThreadProc(Object stateInfo) {
        TaskInfo ti = (TaskInfo) stateInfo;
        Console.WriteLine(ti.Boilerplate, ti.Value); 
    }
}

// This example shows how to create an object containing task
// information, and pass that object to a task queued for
// execution by the thread pool.
import System.*;
import System.Threading.*;
import System.Threading.Thread;

// TaskInfo holds state information for a task that will be
// executed by a ThreadPool thread.
public class TaskInfo
{
    // State information for the task.  These members
    // can be implemented as read-only properties, read/write
    // properties with validation, and so on, as required.
    public String boilerplate;
    public int value;

    // Public constructor provides an easy way to supply all
    // the information needed for the task.
    public TaskInfo(String text, int number)
    {
        boilerplate = text;
        value = number;
    } //TaskInfo
} //TaskInfo

public class Example
{
    public static void main(String[] args)
    {
        // Create an object containing the information needed
        // for the task.
        TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);

        // Queue the task and data.
        if (ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti)) {
            Console.WriteLine("Main thread does some work, then sleeps.");

            // If you comment out the Sleep, the main thread exits before
            // the ThreadPool task has a chance to run.  ThreadPool 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.");
        }
        else {
            Console.WriteLine("Unable to queue ThreadPool request.");
        }
    } //main

    // The thread procedure performs the independent task, in this case
    // formatting and printing a very simple report.
    //
    static void ThreadProc(Object stateInfo)
    {
        TaskInfo ti = ((TaskInfo)(stateInfo));

        Console.WriteLine(ti.boilerplate, String.valueOf(ti.value));
    } //ThreadProc
} //Example

Windows 98, Windows 2000 Service Pack 4, Windows CE, Windows Millennium, Windows Mobile para Pocket PC, Windows Mobile para Smartphone, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter

Microsoft .NET Framework 3.0 es compatible con Windows Vista, Microsoft Windows XP SP2 y Windows Server 2003 SP1.

.NET Framework

Compatible con: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Compatible con: 2.0, 1.0

XNA Framework

Compatible con: 1.0
Mostrar: