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

반환

값 팩터리에 대한 관련성을 복원하기 위해 삭제할 값입니다.

설명

경우에 따라 값 팩터리 내에서 비동기 작업이 해제될 수 있습니다. 값 팩터리를 완료하기 전에 값 팩터리에서 이 작업을 완료 할 필요가 없는 경우 이 메서드를 사용하여 해당 코드를 값 팩터리와 관련이 없는 것으로 표시하는 것이 유용할 수 있습니다. 특히, 이 작업은 실제로 값 팩터리 자체의 완료를 기다릴 수 있는 코드를 포함할 수 있는 경우에 필요할 수 있습니다. 이러한 상황은 값 팩터리를 InvalidOperationException 아직 완료하지 않은 경우 에서 GetValueAsync(CancellationToken) throw될 수 있으며, 이로 인해 프로그램에서 결정적이지 않은 오류가 발생할 수 있습니다.

코드가 분리된 블록은 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() 합니다.

적용 대상