Run a long running operation on another thread
// waits for the task to complete because of "await" keyword// control returns to the caller method while task executes
// code following Task.Run() executes after the task completes
// this is ideal for executing code from "click"
// and event handlers in a GUI application for a
// responsive user experience
int retVal = await Task.Run(
() =>
{
// long running operation
return 1;
}
);
Run two long running operations one after the other on another thread
// note how the second task uses the result from first taskretVal = await Task.Run(
() => { return 1; }
).ContinueWith(t => { return 1 + t.Result; });
Communicate cancellation request to a Task
static CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();static CancellationToken cancellationToken = cancellationTokenSource.Token;
int retVal = await Task.Run(
() =>
{
// long running operation
if (cancellationToken.IsCancellationRequested)
// OperationCanceledException is caught by the method
// running the task and shown to user
cancellationToken.ThrowIfCancellationRequested();
return 1;
}, cancellationToken
);
To cancel:
CancellationTokenSource.Cancel();
Report Progress
// This lambda will be run on the UI thread.
var progress = new Progress<string>(msg =>
{
textBox.Text = msg;
});
// "progress" is passed as IProgress<string> progress to the
// long running method so that
// it can report progress
Block execution until a task completes
Task<int> task = Task.Run(() =>
{
// long running operation
return 1;
}
);
// Halt further execution until the task completes
Task.WaitAll(task);
// See the "await" examples above. With "await" the execution
// returns to the caller while a task runs