Sprache

AsyncLazy<T>.SuppressRelevance Methode

Definition

Kennzeichnet den folgenden Code als irrelevant für die Empfangswertfactory 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

Gibt zurück

Ein Wert, der gelöscht werden soll, um die Relevanz in der Wertfactory wiederherzustellen.

Hinweise

In einigen Fällen kann asynchrone Arbeit innerhalb einer Wertfactory ausgelagert werden. Wenn die Wertfactory diese Arbeit nicht fertig stellen muss, bevor die Wertfactory abgeschlossen werden kann, kann es hilfreich sein, diese Methode zu verwenden, um diesen Code als irrelevant für die Wertfactory zu kennzeichnen. Dies kann insbesondere erforderlich sein, wenn der Spun off-Vorgang tatsächlich Code enthält, der selbst auf den Abschluss der Wertfactory selbst wartet. Eine solche Situation würde zu einem InvalidOperationException Auslösen GetValueAsync(CancellationToken) führen, wenn die Wertfabrik noch nicht abgeschlossen ist, was nicht determinstische Fehler in das Programm bringen kann.

Ein using Block um den Spun-Off-Code kann Ihrem Programm helfen, zuverlässiges Verhalten zu erzielen, wie unten dargestellt.

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);
  }
}

Wenn die AsyncLazy<T> Methode mit einer JoinableTaskFactoryerstellt wurde, ruft diese Methode auch die Context zugeordnete Factory aufSuppressRelevance().

Gilt für: