AsyncOperationManager 类

定义

提供支持异步方法调用的类的并发管理。 此类不能被继承。

C#
public static class AsyncOperationManager
继承
AsyncOperationManager

示例

下面的代码示例演示如何使用 AsyncOperationManager 类创建支持任何应用程序模型的异步操作的类。 它演示如何实现一个类,该类测试数字以确定它是否为质数。 此计算可能很耗时,因此是在单独的线程上完成的。 进度报告、增量结果和完成通知由 AsyncOperation 类处理,这可确保在正确的线程或上下文中调用客户端的事件处理程序。

有关完整代码列表,请参阅 如何:实现支持基于事件的异步模式的组件。 有关客户端表单的完整代码列表,请参阅 如何:实现基于事件的异步模式的客户端

C#
// 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);
}

注解

如果类需要根据 基于事件的异步模式概述提供异步行为,则会遇到许多并发管理问题。 其中包括确保在适用于应用程序模型的线程或上下文上调用事件处理程序的要求 (例如,Windows 窗体应用程序、ASP.NET 应用程序、控制台应用程序等) 。 AsyncOperationManager提供了一种便捷的方式来创建在 .NET Framework支持的所有应用程序模型下正确运行的类。

AsyncOperationManager 有一个方法 , CreateOperation该方法返回 System.ComponentModel.AsyncOperation 可用于跟踪特定异步任务的持续时间的 。 System.ComponentModel.AsyncOperation任务的 可用于在任务完成时向客户端发出警报。 它还可用于在不终止操作的情况下发布进度更新和增量结果。

有关实现异步类的详细信息,请参阅 实现基于事件的异步模式

属性

SynchronizationContext

获取或设置用于异步操作的同步上下文。

方法

CreateOperation(Object)

返回可用于对特定异步操作的持续时间进行跟踪的 AsyncOperation

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

另请参阅