Myth Rush
Myth Rush

Reputation: 1107

How to stop async task in c# metro application

I am developing metro application in c#, I am using async and await keywords to create make metro async operatons (downloading data etc.). I always show modal "Please wait" dialog. I would like to add "Cancel" button to this modal dialog to allow cancel the background operation. But I am not sure how to cancel processing task... Is there any example how to do that?

This is the example of my task:

// Starts task
public void StartTask()
{
    // show the modal dialog with progress
    _progressDialog.IsOpen = true;
    _progressDialog.CancelClick += ProgressDialog_CancelClick;
    await ToWork();
    _progressDialog.IsOpen = false;
}


// Task which takes some seconds
private async Task DoWork()
{
   await DownloadData();
   await ProcessData();
}

// Cancel task
private void CancelClick(object sender, RoutedEventArgs e)
{
    // hide the modal dialog with progress        
    _progressDialog.IsOpen = false;
    // TODO: Cancel task
    GoBack(this, e);
}

Upvotes: 3

Views: 1460

Answers (1)

scartag
scartag

Reputation: 17680

You can decide to implement DownloadData and ProcessData such that they take a CancellationToken and pass that to them when you need to cancel.

public Task DownloadData(CancellationToken tok)
{
    tok.ThrowIfCancellationRequested();//check that it hasn't been cancelled.

   //while doing your task check

  if (tok.IsCancellationRequested)
    {
                    // whatever you need to clean up.
                    tok.ThrowIfCancellationRequested();
     }


}

For usage you can create a CancellationTokenSource and pass the token to the method.

var source = new CancellationTokenSource();

await DownloadData(source.Token);

When you need to cancel you can call Cancel() on the source

source.Cancel();

Upvotes: 10

Related Questions