定义一组抽象的 Awaiter 的实现接口,你下次写自己的 await 可等待对象时将更加方便

 

我在几篇文章中都说到了在 .NET 中自己实现 Awaiter 情况。async / await 写异步代码用起来真的很爽,就像写同步一样。然而实现 Awaiter 没有现成的接口,它需要你按照编译器的要求为你的类型添加一些具有特定名称的属性和方法。然而没有接口的帮助,我们编写起来就很难获得工具(如 ReSharper)自动生成代码的支持。

本文将分享我提取的自己实现 Awaiter 的接口。你只需要实现这些接口当中的 2 个,就能正确实现一个 Awaitable 和 Awaiter。


 

 

接口代码

你可以在 GitHub 上找到这段代码:https://github.com/walterlv/sharing-demo/blob/master/src/Walterlv.Core/Threading/AwaiterInterfaces.cs

public interface IAwaitable<out TAwaiter> where TAwaiter : IAwaiter
{
    TAwaiter GetAwaiter();
}

public interface IAwaitable<out TAwaiter, out TResult> where TAwaiter : IAwaiter<TResult>
{
    TAwaiter GetAwaiter();
}

public interface IAwaiter : INotifyCompletion
{
    bool IsCompleted { get; }

    void GetResult();
}

public interface ICriticalAwaiter : IAwaiter, ICriticalNotifyCompletion
{
}

public interface IAwaiter<out TResult> : INotifyCompletion
{
    bool IsCompleted { get; }

    TResult GetResult();
}

public interface ICriticalAwaiter<out TResult> : IAwaiter<TResult>, ICriticalNotifyCompletion
{
}

接口实现

在 ReSharper 工具的帮助下,你可以在继承接口之后快速编写出实现代码来:

使用 ReSharper 快速实现 Awaiter
▲ 使用 ReSharper 快速实现 Awaiter

 

使用 ReSharper 快速实现 Awaitable
▲ 使用 ReSharper 快速实现 Awaitable

于是我们可以迅速得到一对可以编译通过的 Awaitable 和 Awaiter:

public sealed class Awaiter : IAwaiter<string>
{
    public void OnCompleted(Action continuation)
    {
        throw new NotImplementedException();
    }

    public bool IsCompleted { get; }

    public string GetResult()
    {
        throw new NotImplementedException();
    }
}

public sealed class Awaitable : IAwaitable<Awaiter, string>
{
    public Awaiter GetAwaiter()
    {
        throw new NotImplementedException();
    }
}

当然,你也可以在一个类里面实现这两个接口:

public sealed class Awaiter : IAwaiter<string>, IAwaitable<Awaiter, string>
{
    public void OnCompleted(Action continuation)
    {
        throw new NotImplementedException();
    }

    public bool IsCompleted { get; }

    public string GetResult()
    {
        throw new NotImplementedException();
    }

    public Awaiter GetAwaiter()
    {
        return this;
    }
}

实现业务需求

我有另外两篇文章在实现真正可用的 Awaiter:

更多 Awaiter 系列文章

入门篇:

实战篇:

posted @   walterlv  阅读(376)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示