Santhosh Shanmugam
Santhosh Shanmugam

Reputation: 31

Cancel an asynchronous event in the async/await model

My question is based on @aepot's answer to this question. How does cancellation work in this model? How is CancellationToken passed to the InvokeAsync method?

public static class DelegateExtensions
{
    public static Task InvokeAsync<TArgs>(this Func<object, TArgs, Task> func, object sender, TArgs e)
    {
        return func == null ? Task.CompletedTask
            : Task.WhenAll(func.GetInvocationList().Cast<Func<object, TArgs, Task>>().Select(f => f(sender, e)));
    }
}

Upvotes: 1

Views: 393

Answers (1)

JonasH
JonasH

Reputation: 36649

How is CancellationToken passed to the InvokeAsync method?

It is not, if you want to support cancellation you would need to change the method to add such a parameter:

public static Task InvokeAsync<TArgs>(this Func<object, TArgs, CancellationToken , Task> func, 
    object sender,
    TArgs e, 
    CancellationToken cancel)
    {
        return func == null ? Task.CompletedTask
            : Task.WhenAll(func.GetInvocationList()
                    .Cast<Func<object, TArgs, CancellationToken, Task>>()
                    .Select(f => f(sender, e, cancel)));
    }

Cancelling needs to be done cooperatively, i.e. the actual method needs access to the cancellation token.

Upvotes: 4

Related Questions