AsyncOperation 类

定义

跟踪异步操作的生存期。Tracks the lifetime of an asynchronous operation.

public ref class AsyncOperation sealed
public sealed class AsyncOperation
type AsyncOperation = class
Public NotInheritable Class AsyncOperation
继承
AsyncOperation

示例

下面的代码示例演示如何使用 AsyncOperation 对象跟踪异步操作的生存期。The following code example demonstrates using an AsyncOperation object to track the lifetime of asynchronous operations. 此代码示例是为 System.ComponentModel.AsyncOperationManager 类提供的更大示例的一部分。This code example is part of a larger example provided for the System.ComponentModel.AsyncOperationManager class.

有关完整的代码清单,请参阅如何:实现支持基于事件的异步模式的组件For a full code listing, see How to: Implement a Component That Supports the Event-based Asynchronous Pattern. 有关客户端窗体的完整代码列表,请参阅如何:实现基于事件的异步模式的客户端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

注解

根据基于事件的异步模式概述实现类时,可能需要跟踪在类的实例上调用的每个异步操作的生存期。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. AsyncOperation 类提供了跟踪和报告异步任务的进度的方法。The AsyncOperation class provides ways to track and report the progress of an asynchronous task.

下表列出了使用 AsyncOperation 对象的方法:The following list identifies ways to use an AsyncOperation object:

  • 若要向客户端报告进度和中间结果,请从异步辅助代码调用 PostTo report progress and interim results to the client, call Post from your asynchronous worker code.

  • 若要指示异步任务已完成,或者若要取消挂起的异步任务,请调用 PostOperationCompletedTo indicate that an asynchronous task has completed, or to cancel a pending asynchronous task, call PostOperationCompleted.

类应在每个任务启动时通过调用 AsyncOperationManager.CreateOperation 来获取每个异步任务的 AsyncOperation 对象。Your class should get an AsyncOperation object for each asynchronous task by calling AsyncOperationManager.CreateOperation when each task starts. 若要允许客户端区分不同的异步任务,AsyncOperationManager.CreateOperation 为唯一的客户端提供的令牌(将成为 UserSuppliedState 属性)使用参数。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. 然后,客户端代码可以使用它来标识引发进度或完成事件的特定异步任务。It can then be used by client code to identify the particular asynchronous task that is raising progress or completion events.

继承者说明

实现程序必须确保 PostOperationCompleted(SendOrPostCallback, Object)Post(SendOrPostCallback, Object) 调用是异步的,因此,如果类库提供程序在发生同步的特定应用程序模型中采用异步行为,则它们不需要考虑潜在的堆栈溢出。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.

有关实现异步类的详细信息,请参阅实现基于事件的异步模式For more information about implementing asynchronous classes, see Implementing the Event-based Asynchronous Pattern.

属性

SynchronizationContext

获取传递给构造函数的 SynchronizationContext 对象。Gets the SynchronizationContext object that was passed to the constructor.

UserSuppliedState

获取或设置用于唯一标识异步操作的对象。Gets or sets an object used to uniquely identify an asynchronous operation.

方法

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Finalize()

完成异步操作。Finalizes the asynchronous operation.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
OperationCompleted()

结束异步操作的生存期。Ends the lifetime of an asynchronous operation.

Post(SendOrPostCallback, Object)

在适合于应用程序模型的线程或上下文中调用委托。Invokes a delegate on the thread or context appropriate for the application model.

PostOperationCompleted(SendOrPostCallback, Object)

结束异步操作的生存期。Ends the lifetime of an asynchronous operation.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅