JoinableTaskContext.SuppressRelevance Method

Definition

Conceals any JoinableTask the caller is associated with until the returned value is disposed.

public:
 Microsoft::VisualStudio::Threading::JoinableTaskContext::RevertRelevance SuppressRelevance();
public Microsoft.VisualStudio.Threading.JoinableTaskContext.RevertRelevance SuppressRelevance ();
member this.SuppressRelevance : unit -> Microsoft.VisualStudio.Threading.JoinableTaskContext.RevertRelevance
Public Function SuppressRelevance () As JoinableTaskContext.RevertRelevance

Returns

A value to dispose of to restore visibility into the caller's associated JoinableTask, if any.

Remarks

In some cases asynchronous work may be spun off inside a delegate supplied to Run, so that the work does not have privileges to re-enter the Main thread until the Run(Func<Task>) call has returned and the UI thread is idle. To prevent the asynchronous work from automatically being allowed to re-enter the Main thread, wrap the code that calls the asynchronous task in a using block with a call to this method as the expression.

this.JoinableTaskContext.RunSynchronously(async delegate {
    using(this.JoinableTaskContext.SuppressRelevance()) {
        var asyncOperation = Task.Run(async delegate {
            // Some background work.
            await this.JoinableTaskContext.SwitchToMainThreadAsync();
            // Some Main thread work, that cannot begin until the outer RunSynchronously call has returned.
        });
    }

    // Because the asyncOperation is not related to this Main thread work (it was suppressed),
    // the following await *would* deadlock if it were uncommented.
    ////await asyncOperation;
});

Applies to