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) ,这可能会在程序中引入不确定的故障。

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()

适用于