You need to check within your method to see if cancellation has been requested. Here is a snippet from a ViewModel to show the sort of pattern you need.
private CancellationTokenSource cts;
private async void OnStartAsync(object arg)
{
IsStarted = true;
cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
try
{
await Task.Run(() =>
{
while (true)
{
Thread.Sleep(100);
token.ThrowIfCancellationRequested();
}
},token);
}
catch (OperationCanceledException)
{
IsStarted = false;
}
}
private bool isStarted;
public bool IsStarted
{
get
{
return isStarted;
}
set
{
isStarted = value;
StartCommand.RaiseCanExecuteChanged();
CancelCommand.RaiseCanExecuteChanged();
}
}
private void OnCancel(object arg)
{
cts.Cancel();
}