0

次のようなクラスコンストラクターがあります。

AuthenticationService = new 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 に答える