AsyncOperation AsyncOperation AsyncOperation AsyncOperation Class

Definition

Realiza un seguimiento de la duración de una operación asincrónica. Tracks the lifetime of an asynchronous operation.

public ref class AsyncOperation sealed
public sealed class AsyncOperation
type AsyncOperation = class
Public NotInheritable Class AsyncOperation
Inheritance
AsyncOperationAsyncOperationAsyncOperationAsyncOperation

Examples

En el ejemplo de código siguiente se muestra cómo utilizar un AsyncOperation objeto para realizar el seguimiento de la duración de las operaciones asincrónicas.The following code example demonstrates using an AsyncOperation object to track the lifetime of asynchronous operations. Este ejemplo de código forma parte de un ejemplo más extenso proporcionado para el System.ComponentModel.AsyncOperationManager clase.This code example is part of a larger example provided for the System.ComponentModel.AsyncOperationManager class.

Para obtener una lista de código completo, vea Cómo: implementar un componente que admita el modelo asincrónico basado en eventos.For a full code listing, see How to: Implement a Component That Supports the Event-based Asynchronous Pattern. Para obtener una lista de código completo de un formulario de cliente, consulte Cómo: implementar un cliente en el modelo asincrónico basado en eventos.For a full code listing of a client form, see How to: Implement a Client of the Event-based Asynchronous Pattern.

// This method starts an asynchronous calculation. 
// First, it checks the supplied task ID for uniqueness.
// If taskId is unique, it creates a new WorkerEventHandler 
// and calls its BeginInvoke method to start the calculation.
public virtual void CalculatePrimeAsync(
    int numberToTest,
    object taskId)
{
    // Create an AsyncOperation for taskId.
    AsyncOperation asyncOp =
        AsyncOperationManager.CreateOperation(taskId);

    // Multiple threads will access the task dictionary,
    // so it must be locked to serialize access.
    lock (userStateToLifetime.SyncRoot)
    {
        if (userStateToLifetime.Contains(taskId))
        {
            throw new ArgumentException(
                "Task ID parameter must be unique", 
                "taskId");
        }

        userStateToLifetime[taskId] = asyncOp;
    }

    // Start the asynchronous operation.
    WorkerEventHandler workerDelegate = new WorkerEventHandler(CalculateWorker);
    workerDelegate.BeginInvoke(
        numberToTest,
        asyncOp,
        null,
        null);
}
' This method starts an asynchronous calculation. 
' First, it checks the supplied task ID for uniqueness.
' If taskId is unique, it creates a new WorkerEventHandler 
' and calls its BeginInvoke method to start the calculation.
Public Overridable Sub CalculatePrimeAsync( _
    ByVal numberToTest As Integer, _
    ByVal taskId As Object)

    ' Create an AsyncOperation for taskId.
    Dim asyncOp As AsyncOperation = _
        AsyncOperationManager.CreateOperation(taskId)

    ' Multiple threads will access the task dictionary,
    ' so it must be locked to serialize access.
    SyncLock userStateToLifetime.SyncRoot
        If userStateToLifetime.Contains(taskId) Then
            Throw New ArgumentException( _
                "Task ID parameter must be unique", _
                "taskId")
        End If

        userStateToLifetime(taskId) = asyncOp
    End SyncLock

    ' Start the asynchronous operation.
    Dim workerDelegate As New WorkerEventHandler( _
        AddressOf CalculateWorker)

    workerDelegate.BeginInvoke( _
        numberToTest, _
        asyncOp, _
        Nothing, _
        Nothing)

End Sub

Remarks

Cuando se implementa una clase conforme a la Event-based Asynchronous Pattern Overview, es posible que deba realizar un seguimiento de la duración de cada operación asincrónica invocada en una instancia de la clase.When you implement a class according to the Event-based Asynchronous Pattern Overview, you may need to track the lifetime of each asynchronous operation invoked on an instance of your class. La AsyncOperation clase proporciona métodos para realizar un seguimiento y notificar el progreso de una tarea asincrónica.The AsyncOperation class provides ways to track and report the progress of an asynchronous task.

En la lista siguiente identifica las maneras de utilizar un AsyncOperation objeto:The following list identifies ways to use an AsyncOperation object:

  • Para informar del progreso y resultados provisionales al cliente, llame a Post desde el código de trabajo asincrónico.To report progress and interim results to the client, call Post from your asynchronous worker code.

  • Para indicar que se ha completado una tarea asincrónica o cancelar una tarea asincrónica pendiente, llame a PostOperationCompleted.To indicate that an asynchronous task has completed, or to cancel a pending asynchronous task, call PostOperationCompleted.

La clase debe obtener un AsyncOperation objeto para cada tarea asincrónica mediante una llamada a AsyncOperationManager.CreateOperation cuando se inicia cada tarea.Your class should get an AsyncOperation object for each asynchronous task by calling AsyncOperationManager.CreateOperation when each task starts. Para permitir al cliente distinguir las distintas tareas asincrónicas, AsyncOperationManager.CreateOperation toma un parámetro para un token único proporcionado por el cliente, que se convierte en el UserSuppliedState propiedad.To allow the client to distinguish separate asynchronous tasks, AsyncOperationManager.CreateOperation takes a parameter for a unique client-provided token, which becomes the UserSuppliedState property. A continuación, se puede usar código de cliente para identificar la tarea asincrónica determinada que está generando eventos de progreso o finalización.It can then be used by client code to identify the particular asynchronous task that is raising progress or completion events.

Notes to Inheritors

Los implementadores deben garantizar la PostOperationCompleted(SendOrPostCallback, Object) y Post(SendOrPostCallback, Object) las llamadas son asincrónicas, por lo que no es necesario preocuparse por los proveedores de bibliotecas de clase desbordamientos de la pila potencial si adoptan el comportamiento asincrónico en una aplicación concreta modelo que resulta ser sincrónico. Implementers must ensure the PostOperationCompleted(SendOrPostCallback, Object) and Post(SendOrPostCallback, Object) invocations are asynchronous, so that class library providers do not need to concern themselves with potential stack overflows if they assume asynchronous behavior in a particular application model that happens to be synchronous. Para obtener más información acerca de cómo implementar clases asincrónicas, vea implementar el modelo asincrónico basado en eventos. For more information about implementing asynchronous classes, see Implementing the Event-based Asynchronous Pattern.

Properties

SynchronizationContext SynchronizationContext SynchronizationContext SynchronizationContext

Obtiene el objeto SynchronizationContext que se pasó al constructor. Gets the SynchronizationContext object that was passed to the constructor.

UserSuppliedState UserSuppliedState UserSuppliedState UserSuppliedState

Obtiene o establece un objeto que se usa para identificar de forma única una operación asincrónica. Gets or sets an object used to uniquely identify an asynchronous operation.

Methods

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual. Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()

Finaliza la operación asincrónica. Finalizes the asynchronous operation.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada. Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual. Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del Object actual. Creates a shallow copy of the current Object.

(Inherited from Object)
OperationCompleted() OperationCompleted() OperationCompleted() OperationCompleted()

Pone fin a la duración de una operación asincrónica. Ends the lifetime of an asynchronous operation.

Post(SendOrPostCallback, Object) Post(SendOrPostCallback, Object) Post(SendOrPostCallback, Object) Post(SendOrPostCallback, Object)

Invoca un delegado en el subproceso o contexto adecuado para el modelo de aplicaciones. Invokes a delegate on the thread or context appropriate for the application model.

PostOperationCompleted(SendOrPostCallback, Object) PostOperationCompleted(SendOrPostCallback, Object) PostOperationCompleted(SendOrPostCallback, Object) PostOperationCompleted(SendOrPostCallback, Object)

Pone fin a la duración de una operación asincrónica. Ends the lifetime of an asynchronous operation.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual. Returns a string that represents the current object.

(Inherited from Object)

Applies to

See Also