The NanoByte.Common.Tasks namespace provides a framework for managing long-running tasks and reporting progress to the user.
Tasks are represented using the ITask interface.
The ITaskHandler interface represents a user interface for reporting task progress as well as displaying prompts and outputs to the user. This library provides a number of implementations:
- CliTaskHandler for a basic command-line interface
- AnsiCliTaskHandler for a more advanced command-line interface using ANSI codes
- DialogTaskHandler for a graphical interface using WinForms dialog boxes
- SilentTaskHandler for background execution or unit tests
- ServiceTaskHandler for integration with Microsoft.Extensions.DependencyInjection
Methods that wish to run ITasks should take an ITaskHandler as an input parameter.
To run an ITask pass it to the ITaskHandler.RunTask() method. This will then internally call ITask.Run() and take care of setting up progress tracking, cancellation, etc.. Additional methods such as ITaskHandler.Ask() can be used for user interaction.
ITaskHandler implementations are thread-safe and support running multiple ITasks concurrently.
ITaskHandler.RunTask() blocks until the tasks is complete, however some implementations may perform the actual task execution on a separate thread.
DialogTaskHandler keeps the WinForms message loop pumping while a task is running, so calling
.RunTask() from the GUI thread will not freeze the GUI. However it does prevent user actions (other than canceling the task) via a modal dialog box.
Comparison with async/await
await keywords are part of the Task Asynchronous Programming model (TAP). The TAP provides an abstraction over asynchronous code, enabling the execution of continuations after tasks have completed. This is intended to increase the performance and responsiveness of applications. Many TAP methods accept CancellationTokens to signal that a task should be cancelled and Progress<T> to report a task's progress.
NanoByte.Common's Task system is intended for managing long-running tasks. It provides an abstraction over UIs for interacting with such tasks. It uses the same CancellationToken and Progress<T> as the TAP, but takes care of managing them internally for most use cases.
As a rule of thumb: