Parallel (4.0)
Parallel.Invoke, myTaskFactory.StartNew()
CancellationTokenSource cts = new CancellationTokenSource();
Action<int> c = new Action<int>(delegate(int i)
{
while (cts.IsCancellationRequested == false)
{
Console.WriteLine("Action " + i);
}
});
ParallelOptions options = new ParallelOptions();
options.CancellationToken = cts.Token;
// Parallel.Invoke(options, () => c(1), () => c(2), () => c(3)); <-- This would wait forever as Parallel.Invoke waits for all actions to complete
TaskFactory fred = new TaskFactory(cts.Token);
fred.StartNew(() => { c(10); }); <-- Overloads allow cleaver stuff like 'run this task only if parent task errore
fred.StartNew(() => { c(20); });
fred.StartNew(() => { c(30); });
Thread.Sleep(1000);
cts.Cancel();
Console.WriteLine("****Cancel");
PLINQ
// IEnumerable<int> myEnumerable = from i in Enumerable.Range(0, 100) select i;
ParallelQuery<int> myEnumerable = from i in Enumerable.Range(0, 100).AsParallel() select i;
Parallel.ForEach(myEnumerable, (i) =>
{
Console.WriteLine(i);
});
CTP
var c = new ActionBlock(i => {DoSomething(i);});
for(int n = 1; n < 10; n++) c.Post(i); // Queued
await Task.WhenAll(t1, t2);