Editar

Compartilhar via


AsyncCollectionRequestMessage<T>.CancellationToken Property

Definition

Gets the CancellationToken instance that will be linked to the one used to asynchronously enumerate the received responses. This can be used to cancel asynchronous replies that are still being processed, if no new items are needed from this request message. Consider the following example, where we define a message to retrieve the currently opened documents:

public class OpenDocumentsRequestMessage : AsyncCollectionRequestMessage<XmlDocument> { }

We can then request and enumerate the results like so:

await foreach (var document in Messenger.Default.Send<OpenDocumentsRequestMessage>())
{
    // Process each document here...
}

If we also want to control the cancellation of the token passed to each subscriber to the message, we can do so by passing a token we control to the returned message before starting the enumeration (WithCancellation<T>(IAsyncEnumerable<T>, CancellationToken)). The previous snippet with this additional change looks as follows:

await foreach (var document in Messenger.Default.Send<OpenDocumentsRequestMessage>().WithCancellation(cts.Token))
{
    // Process each document here...
}

When no more new items are needed (or for any other reason depending on the situation), the token passed to the enumerator can be canceled (by calling Cancel()), and that will also notify the remaining tasks in the request message. The token exposed by the message itself will automatically be linked and canceled with the one passed to the enumerator.

public System.Threading.CancellationToken CancellationToken { get; }
member this.CancellationToken : System.Threading.CancellationToken
Public ReadOnly Property CancellationToken As CancellationToken

Property Value

Applies to