- 1. What is a TaskScheduler?
A TaskScheduler represents an object that handles the low-level work of scheduling threads. The Framework provides two concrete implementations: the default scheduler which works in tandem with ThreadPool and the synchronization context scheduler, which is used by WPF and WinForms. Which task scheduler a task should use we can point out manually.
public partial class Form1 : Form
{
private readonly TaskScheduler _taskScheduler = null;
private CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
public Form1()
{
InitializeComponent();
Text = “some text”;
Width = 500;
Height = 200;
Visible = true;
_taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
}
private void InitializeComponent(){}
private int DoSomeCalc(int n)
{
for (int i = 0; i < n; i++)
{
Thread.Sleep(100);
n++;
}
return n;
}
protected override void OnMouseClick(MouseEventArgs e)
{
if (_cancellationTokenSource != null)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource = null;
}
else
{
_cancellationTokenSource = new CancellationTokenSource();
Task<int> task = new Task<int>(() => DoSomeCalc(10), _cancellationTokenSource.Token);
task.Start();
task.ContinueWith(t => { Text = “Thread completed, the result is: ” + t.Result.ToString(); }, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, _taskScheduler);
task.ContinueWith(t => { Text = “Thread was canceled, the result is: ” + t.Result.ToString(); }, CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled, _taskScheduler);
task.ContinueWith(t => { Text = “Thread faulted, the result is: ” + t.Result.ToString(); }, CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, _taskScheduler);
}
base.OnMouseClick(e);
}
}
It’s possible to write our own TaskScheduler.