Free mag vol1 | Page 797

CHAPTER 19  MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING The necessary extension methods are found within the ParallelEnumerable class of the System.Linq namespace. Table 19-5 documents some useful PLINQ extensions. Table 19-5. Select Members of the ParallelEnumerable class Member Meaning in Life AsParallel() Specifies that the rest of the query should be parallelized, if possible. WithCancellation() Specifies that PLINQ should periodically monitor the state of the provided cancellation token and cancel execution if it is requested. WithDegreeOfParallelism() Specifies the maximum number of processors that PLINQ should use to parallelize the query. ForAll() Enables results to be processed in parallel without first merging back to the consumer thread, as would be the case when enumerating a LINQ result using the foreach keyword. To see PLINQ in action, create a final Windows Forms application named PLINQDataProcessingWithCancellation and import the System.Threading namespace. This simple form will only need two Button controls named btnExecute and btnCancel. Then the “Execute” button is clicked, and you will fire off a new Task, which executes a LINQ query that investigates a very large array of integers, looking for only the items where x % 3 == 0 is true. Here is a nonparallel version of the query: public partial class MainForm : Form { ... private void btnExecute_Click(object sender, EventArgs e) { // Start a new "task" to process the ints. Task.Factory.StartNew(() => { ProcessIntData(); }); } private void ProcessIntData() { // Get a very large array of integers. int[] source = Enumerable.Range(1, 10000000).ToArray(); // Find the numbers where num % 3 == 0 is true, returned // in descending order. int[] modThreeIsZero = (from num in source where num % 3 == 0 orderby num descending select num).ToArray(); MessageBox.Show(string.Format("Found {0} numbers that match query!", modThreeIsZero.Count())); 742