You have to implement most of the cancellation code yourself, but there are a few things you have to enable on the backgroundworker itself.
The WorkerSupportsCancellation property must be set.
Then when you want to cancel, you call CancelAsync, doing this sets the cancellationpending property of the backgroundworker to true.
You have to check this property at regular intervals to check if the user requested the cancel, if you don't do this, well, it will keep on running.
private void workerDoWork(object sender, DoWorkEventArgs e)
{
for(int i = 0;i<1000000;i++){
TimeConsumingMethod();
if (myworker.CancellationPending){
e.Cancel = true;
return;
}
}
}
private void btnCancel_Click(object sender,RoutedEventArgs e)
{
myWorker.CancelAsync();
}