I have a task that looks like this:
var task = Task.Factory.StartNew
I personally find the following approach to be the most elegant:
// Cancellation token for the latest task.
private CancellationTokenSource cancellationTokenSource;
private void OnClick(object sender, ItemClickEventArgs e)
{
// If a cancellation token already exists (for a previous task),
// cancel it.
if (this.cancellationTokenSource != null)
this.cancellationTokenSource.Cancel();
// Create a new cancellation token for the new task.
this.cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = this.cancellationTokenSource.Token;
// Start the new task.
var task = Task.Factory.StartNew