I am looking into adding cancellation support to awaitable extension methods in the AsyncUI and WinRT XAML Toolkit libraries. It seems like the base Task class does not have a built-in Cancel() method or event and relies on cancellation tokens that my tasks would need to check for periodically. I think does not make sense in my UI scenarios, since my tasks are generated using the TaskCompletionSource and I would like to cancel the tasks on the UI thread in response to events instead of running a loop on a thread pool thread and checking for a token.
My tasks currently complete when a UI event happens – like a Storyboard completing or a button being clicked, so if I want to support cancellation – I need to respond to a cancellation request by unsubscribing from events and doing other cleanup like stopping an animation .
I am thinking of creating some sort of CancellableUITask base class instead of using the TaskCompletionSource, so I could expose a Cancel() method that the consumer of my task could call (e.g. to stop an awaited animation in response to a button click) and something like a virtual OnCancellationRequested() method that my storyboard awaiter task could override to perform cleanup.
Does it make sense? What would be the best way to accomplish what I am describing here?
Your tasks would not need to check periodically for cancellation – that is just the most common way of doing things. If your tasks are event-driven, then you can register a handler against the
CancellationTokenthat will be called when it is cancelled. SeeCancellationToken.Register.So your code might look something like this: