concept TPL in category .net

This is an excerpt from Manning's book Concurrency in .NET.
The Microsoft Task Parallel Library (TPL), introduced after the release of .NET 4.0, makes it easier to implement and exploit parallelism for this type of algorithm. Using the TPL, you can divide each step of the algorithm and perform each task in parallel, recursively. It’s a straight and easy implementation, but you must be careful of the level of depth to which the threads are created to avoid adding more tasks than necessary.
Listing 1.2 Parallel Quicksort algorithm using the TPL
let rec quicksortParallel aList = match aList with | [] -> [] | firstElement :: restOfList -> let smaller, larger = List.partition (fun number -> number < firstElement) restOfList let left = Task.Run(fun () -> quicksortParallel smaller) #1 let right = Task.Run(fun () -> quicksortParallel larger) #1 left.Result @ (firstElement :: right.Result) #2 #1 Task.Run executes the recursive calls in tasks that can run in parallel; for each recursive call, tasks are dynamically created. #2 Appends the result for each task into a sorted array
Figure 7.3 The TPL uses the work-stealing algorithm to optimize the scheduler. Initially, the TPL sends jobs to the main queue (step 1). Then it dispatches the work items to one of the worker threads, which has a private and dedicated queue of work items to process (step 2). If the main queue is empty, the workers look in the private queues of the other workers to “steal” work (step 3).
![]()
The previous section discussed the concept of
TaskandResulttypes combined for providing safe and declarative error handling in a functional style. In addition to the TPL, the asynchronous workflow computation expression in F# offers a more idiomatic functional approach. This section covers the recipe for taming exceptions by showing how to combine the F#Asynctype with theResultstructure.