// create and run a task in a new threadvarresult = await Task.Run(async () =>
{
awaitTask.Delay(4000);
return0;
});
Cancel a task
varcancellationTokenSource = newCancellationTokenSource(5000); // cancel after 5sCancellationTokentoken = cancellationTokenSource.Token;
try
{
await Task.Run(async () =>
{
var i = 1;
while (!token.IsCancellationRequested) // break the loop if cancellation is requested
{
Console.Write($"{i++} ");
await Task.Delay(1000);
}
token.ThrowIfCancellationRequested(); // or throw an OperationCanceledException
}, token);
}
catch (OperationCanceledExceptione)
{
Console.WriteLine(e.Message);
}
cancellationTokenSource.Token.Register(() => {
/* what to when the token is cancelled */
});
Fire and forget
Call an async method without waiting for the response. Exceptions will be lost.
// for loop
Parallel.For(1, 20, i =>
{
Console.WriteLine(i);
Thread.Sleep(1000);
});
// for each loop
Parallel.ForEach(Enumerable.Range(1, 20), i =>
{
Console.WriteLine(i);
Thread.Sleep(1000);
});
// invoke actions
Parallel.Invoke(
() => {
Console.WriteLine(1);
Thread.Sleep(1000);
},
() => {
Console.WriteLine(2);
Thread.Sleep(1000);
}
);
Parallel options
// after 4s throw an OperationCanceledException// no further operations will start but don't stop currently executing operationsvarcancellationTokenSource = newCancellationTokenSource(4000);
varparallelOptions = newParallelOptions
{
MaxDegreeOfParallelism = 12, // by default use as much computer power as possible
TaskScheduler = null,
CancellationToken = cancellationTokenSource.Token
}
Parallel.ForEach(
numbers,
parallelOptions,
(inti, ParallelLoopStateloopState) =>
{
if (loopState.ShouldExitCurrentIteration) // check if another iteration has requested to break
{
loopState.Break(); // break loop
}
if (!cancellationTokenSource.Token.IsCancellationRequested) { /* next operation step */ } // useful for long operation to break
});
Handling exceptions
All the exceptions are catched and when all the tasks have been executed then an AggregateException is thrown if any.
privatestaticreadonlyobjectsumLock = new();
varsum = 0m; // shared variable, updated by threads
Parallel.For(0, 100, i =>
{
lock(sumLock) // only 1 thread at a time can access
{
sum += 0.5m; // code inside the lock should take as little time as possible
}
});
To avoid deadlocks:
use 1 lock object for each shared resource
avoid nested locks
use a new object
Interlocked
Create thread-safe atomic operations.
Faster than lock, but Interlocked only works with integers.
intsum = 0; // shared variable, updated by threads
Parallel.For(0, 100, i =>
{
Interlocked.Add(refsum, 1);
});
AsyncLocal
Allow to have a different variable for each async task.
privatestaticAsyncLocal<decimal?> asyncLocal = new();
Parallel.For(0, 100, async (i) =>
{
asyncLocal.Value = 10; // the asyncLocal is not shared among async tasks
});
Concurrent collections
BlockingCollection<T>
ajout et suppression thread-safe. Add, Take. FIFO par défaut.
ConcurrentBag<T>
sans ordre, doublons autorisés. Add, TryTake, TryPeek.
ConcurrentDictionary<TKey,T>
TryAdd, TryUpdate, AddOrUpdate, GetOrAdd.
ConcurrentQueue<T>
FIFO. Enqueue, TryDequeue.
ConcurrentStack<T>
LIFO. Push, TryPop.
BlockingCollection<string> col = newBlockingCollection<string>();
col.Add("text");
strings = col.Take();
foreach (string v in col.GetConsumingEnumerable())
Console.WriteLine(v);
Tasks
// AsParallel PLINQvartasks = Enumerable.Range(1, 30).AsParallel().Select(x => MyTaskAsync(x));
await Task.WhenAll(tasks);
// ForEachAsyncawait Parallel.ForEachAsync(Enumerable.Range(1, 30), async (x, token) => awaitMyTaskAsync(x));
// Task.Run run task in a new thread// even without Task.Run, Task.WhenAll will run the tasks in parallel and then for all of them to be donevartasks = Enumerable.Range(1, 30).Select(x => Task.Run(() => MyTaskAsync(x)));
await Task.WhenAll(tasks);
privateasyncTaskMyTaskAsync(inti)
{
Console.WriteLine(i);
await Task.Delay(4000);
}
Handle exceptions with Task.WhenAll
The problem
// create 10 jobs in parallel, the jobs 5 and 7 will raise an Exceptiontry
{
varcreateJobTasks = Enumerable.Range(1, 10).Select(x => CreateJobAsync($"Job {x}"));
}
catch (Exceptione) { } // only the first exception is catched!
asyncTask<Job> CreateJobAsync(stringname)
{
await Task.Delay(1);
if (name.EndsWith("5") || name.EndsWith("7") )
thrownewException($"Error {name}");
returnnewJob { Name = name };
}
classJob
{
publicstring Name { get; set; }
}
// create 10 jobs in parallel, the job 5 will raise an Exception// the created jobs are wrapped into TaskResult to handle ExceptionvarcreateJobTasks = Enumerable.Range(1, 10).Select(x => CreateJobAsync($"Job {x}").ToTaskResultAsync());
varjobs = await Task.WhenAll(createJobTasks);
// if the TaskResult is a succes then access to the Result otherwise access to the Exception ErrorMessagevarwriteTasks = jobs.Select(x => Task.Run(() => Console.WriteLine(x.Success ? x.Result.Name : x.ErrorMessage)));
await Task.WhenAll(writeTasks);
AsParallel analyses the query to see if it is suitable for parallelization. This analysis adds overhead.
If it is unsafe or faster to run sequentially then it won't be run in parallel.
varnumbers = Enumerable.Range(0, 100_000_000);
varparallelResult = numbers.AsParallel()
.WithDegreeOfParallelism(2)
.WithCancellation(token)
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.WithMergeOptions(ParallelMergeOptions.Default)
.AsOrdered() // add overhead
.Where(i => i % 2 == 0);
// parcourt d'itération en mode parallèle, l'ordre est perdu.// le parcourt commence même si parallelResult n'est pas au complet
parallelResult.ForAll(e => Console.WriteLine(e));