内容简介:我在几篇文章中都说到了在 .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 工具的帮助下,你可以在继承接口之后快速编写出实现代码来:
▲ 使用 ReSharper 快速实现 Awaiter
▲ 使用 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 系列文章
入门篇:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Rationality for Mortals
Gerd Gigerenzer / Oxford University Press, USA / 2008-05-02 / USD 65.00
Gerd Gigerenzer's influential work examines the rationality of individuals not from the perspective of logic or probability, but from the point of view of adaptation to the real world of human behavio......一起来看看 《Rationality for Mortals》 这本书的介绍吧!