我试图根据Stephen Cleary的博客文章(http://blog.stephencleary.com/2012/08/asynchronous-lazy-initialization.html)在静态类中加入异步延迟初始化:
internal static class ThirdPartyCommunicator
{
private static readonly AsyncLazy<IClient> myClient = new AsyncLazy<IClient>
(
async () => { var client = await CreateClient(); return client; }
);
private static async Task<IClient> CreateClient()
{
var identity = service.GetIdentity();
await identity.AuthenticationAsync();
return identity.Client();
}
internal static async void DoWork()
{
var client = await this.myClient; //compilation error
....
在DoWork()
中,我收到错误:
无法访问静态字段&#34; myClient&#34;在非静态环境中
我不清楚导致此问题的非静态背景。
答案 0 :(得分:1)
static
方法无论如何都不能使用this
关键字。当this
:)
static
删除this
关键字,所有内容都可以正常编译,因为myClient也是static
。