AsyncLazy<T>.SuppressRelevance 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將後面的程式代碼標示為與接收 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
傳回
要處置的值,以將相關性還原至實值處理站。
備註
在某些情況下,異步工作可能會在實值處理站內關閉。 當值處理站 不需要 在值處理站完成之前完成此工作時,使用此方法將該程式代碼標示為與值處理站無關會很有用。 特別是,當 Spun off 工作可能實際包含程式代碼,而程式代碼可能會等候值處理站本身完成時,就可能是必要的。 如果值處理站尚未完成,則這類情況 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() 。