0

我有一个类构造函数,例如:

AuthenticationService = new AuthenticationService();

然而,这种“变量初始化”可能需要几秒钟,有时父类可能仍然不需要它。我怎样才能使用并行编程来初始化它,并且仍然让“父亲”类继续,只有在他需要使用它并且对象 AuthenticationService 仍未准备好时才等待。

我怎样才能做到这一点?

我的解决方案(感谢 Jon Skeet)

    private Task<AuthenticationService> authTask;
    public AuthenticationService AuthenticationService
    {
        get
        {
            return authTask.Result;
        }
    }

    public MyConstructor(){
          authTask = Task.Factory.StartNew(() => new AuthenticationService());
    }
4

1 回答 1

1

您可以使用Task

Task<AuthenticationService> authTask = 
    Task.Factory.StartNew(() => new AuthenticationService);

// Do other things here...

// Now if we *really* need it, block until we've got it.
AuthenticationService authService = authTask.Result;

请注意,该Result属性将阻塞当前线程,直到结果可用。如果您使用的是 C# 5,则可能需要考虑使用异步方法,在这种情况下您可以await执行任务。

于 2013-05-22T12:15:42.603 回答