TaskCompletionSource 类型

原文地址 : https://www.pluralsight.com/guides/task-taskcompletion-source-csharp

定义: 可以将任何异步操作转换为Task

用例: Asp.Net Core 7 中的 IHost 接口的扩展方法 WaitForShutdownAsync

    public static async Task WaitForShutdownAsync(this IHost host, CancellationToken token = default(CancellationToken))
    {
        IHostApplicationLifetime requiredService = host.Services.GetRequiredService<IHostApplicationLifetime>();
        token.Register(delegate(object state)
        {
            ((IHostApplicationLifetime)state).StopApplication();
        }, requiredService);
        TaskCompletionSource<object> taskCompletionSource = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
        requiredService.ApplicationStopping.Register(delegate(object obj)
        {
            TaskCompletionSource<object> taskCompletionSource2 = (TaskCompletionSource<object>)obj;
            taskCompletionSource2.TrySetResult(null);
        }, taskCompletionSource);
        await taskCompletionSource.Task.ConfigureAwait(continueOnCapturedContext: false);
        await host.StopAsync(CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false);
    }

 TaskCompletionSource 将 ApplicationStopping 的回调方法转化为 await taskCompletionSource.Task.ConfigureAwait(continueOnCapturedContext: false);

posted @ 2022-11-18 17:27  顾小凡  阅读(118)  评论(0)    收藏  举报