静态类中的异步延迟初始化不编译

时间:2014-12-05 14:21:13

标签: c#

我试图根据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;在非静态环境中

我不清楚导致此问题的非静态背景。

1 个答案:

答案 0 :(得分:1)

static方法无论如何都不能使用this关键字。当this:)

时,没有static

删除this关键字,所有内容都可以正常编译,因为myClient也是static