Compartilhar via


IAsyncServiceProvider3.GetServiceAsync<TService,TInterface> Method

Definition

Retrieves a proffered service asynchronously, specifying whether to throw an exception if it could not be retrieved.

public System.Threading.Tasks.Task<TInterface?> GetServiceAsync<TService,TInterface> (bool throwOnFailure, System.Threading.CancellationToken cancellationToken) where TInterface : class;
abstract member GetServiceAsync : bool * System.Threading.CancellationToken -> System.Threading.Tasks.Task<'Interface (requires 'Interface : null)> (requires 'Interface : null)
Public Function GetServiceAsync(Of TService, TInterface) (throwOnFailure As Boolean, cancellationToken As CancellationToken) As Task(Of TInterface)

Type Parameters

TService

The service identity of the proffered service to retrieve.

TInterface

The interface used to interact with the proffered service. If TService is not registered as async or free-threaded, then this cast will be performed on the main thread.

Parameters

throwOnFailure
Boolean

true to throw an exception if the service could not be retrieved; otherwise, false to return null on failure.

cancellationToken
CancellationToken

A token whose cancellation indicates that the caller no longer is interested in the result. This will not cancel the in-progress loading of packages and/or creation of services as a result of the service retrieval, but this token will result in an expedient cancellation of the returned Task.

Returns

Task<TInterface>

A task representing the service retrieval whose result is the service or null if there was a failure and throwOnFailure is false.

Exceptions

cancellationToken has been canceled.

throwOnFailure is true and there was a failure retrieving the service due to one of the following conditions:

  • The service threw an exception during activation. InnerException may include details about the underlying failure.
  • The associated package failed to load. InnerException may include details about the underlying failure.
  • The associated package could not be found, or the package did not correctly proffer the service.
  • The associated package proffered null.
  • The service does not support the requested interface specified by TInterface.
  • The environment has starting shutting down and the retrieval would have resulted in a package load.

Remarks

Prefer this method over an explicit cast to TInterface to avoid a blocking RPC call if the underlying service is STA-bound, which can hang if the UI thread is blocked in a Run(Func<Task>) or Join(CancellationToken).

Note the difference in behavior this method has around exceptions to its non-generic equivalents GetServiceAsync(Type) and GetServiceAsync(Type, Boolean).

This method is safe to access from any thread.

Applies to