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

栏目: ASP.NET · 发布时间: 7年前

内容简介:我在几篇文章中都说到了在 .NET 中自己实现 Awaiter 情况。本文将分享我提取的自己实现 Awaiter 的接口。你只需要实现这些接口当中的 2 个,就能正确实现一个 Awaitable 和 Awaiter。你可以在 GitHub 上找到这段代码:

我在几篇文章中都说到了在 .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 工具的帮助下,你可以在继承接口之后快速编写出实现代码来:

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

定义一组抽象的 Awaiter 的实现接口,你下次写自己的 await 可等待对象时将更加方便 ▲ 使用 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 系列文章

入门篇:


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

DOM Scripting

DOM Scripting

Jeremy Keith / friendsofED / 2010-12 / GBP 27.50

There are three main technologies married together to create usable, standards-compliant web designs: XHTML for data structure, Cascading Style Sheets for styling your data, and JavaScript for adding ......一起来看看 《DOM Scripting》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具