Sometimes you may need to cancel a running asynchronous task, this following tutorial will show you how. Here’s how your task will work without an
Step 1: Create a new Windows Phone 8/8.1 Project
Start Visual Studio and create a new Windows Phone 8/8.1 project.
Step 2: In the MainPage.xaml paste the following code
Step 3: In the MainPage.xaml.cs above the constructor declare our CancellationTokenSource
CancellationTokenSource.Token property of
cancellationToken is passed into our asynchronous task as an argument, while doing work the task can check the token to see if cancellation has been requested.
Step 4: Thereafter paste the following methods below the constructor
When the restart button is clicked, we cancel the current
CancellationTokenSource which will stop the running task, we then instantiate a new
CancellationTokenSource & start a new task. Here’s how it works,
Download the project source code and use it as a reference.