Language

AsyncLazy<T>.SuppressRelevance メソッド

定義

次のコードは、受信 AsyncLazy<T> 値ファクトリとは無関係としてマークします。

public Microsoft.VisualStudio.Threading.AsyncLazy<T>.RevertRelevance SuppressRelevance();
member this.SuppressRelevance : unit -> Microsoft.VisualStudio.Threading.AsyncLazy<'T>.RevertRelevance
Public Function SuppressRelevance () As AsyncLazy(Of T).RevertRelevance

返品

値ファクトリに関連性を復元するために破棄する値。

注釈

場合によっては、非同期作業がバリュー ファクトリ内でスピンオフされる場合があります。 値ファクトリが完了する前にこの作業を完了する必要 がない 場合は、このメソッドを使用して、そのコードを値ファクトリとは無関係としてマークすると便利です。 特に、スピンオフ タスクに実際に値ファクトリ自体の完了を待つコードが含まれている場合に、これが必要になる場合があります。 このような状況では、値ファクトリがまだ完了していない場合、GetValueAsync(CancellationToken)からInvalidOperationExceptionがスローされ、プログラムで非決定的なエラーが発生する可能性があります。

スピンオフ コードの周りの using ブロックは、次に示すように、プログラムが信頼性の高い動作を実現するのに役立ちます。

class MyClass {
  private readonly AsyncLazy<int> numberOfApples;

  public MyClass() {
    this.numberOfApples = new AsyncLazy<int>(async delegate {
      // We have some fire-and-forget code to run.
      // This is *not* relevant to the value factory, which is allowed to complete without waiting for this code to finish.
      using (this.numberOfApples.SuppressRelevance()) {
        this.FireOffNotificationsAsync();
      }

      // This code is relevant to the value factory, and must complete before the value factory can complete.
      return await this.CountNumberOfApplesAsync();
    });
  }

  public event EventHandler? ApplesCountingHasBegun;

  public async Task<int> GetApplesCountAsync(CancellationToken cancellationToken) {
    return await this.numberOfApples.GetValueAsync(cancellationToken);
  }

  private async Task<int> CountNumberOfApplesAsync() {
    await Task.Delay(1000);
    return 5;
  }

  private async Task FireOffNotificationsAsync() {
    // This may call to 3rd party code, which may happen to call back into GetApplesCountAsync (and thus into our AsyncLazy instance),
    // but such calls should *not* be interpreted as value factory reentrancy. They should just wait for the value factory to finish.
    // We accomplish this by suppressing relevance of the value factory while this code runs (see the caller of this method above).
    this.ApplesCountingHasBegun?.Invoke(this, EventArgs.Empty);
  }
}

AsyncLazy<T>がJoinableTaskFactoryで作成された場合、このメソッドは、そのファクトリに関連付けられているContextのSuppressRelevance()も呼び出します。

適用対象