CHAPTER 19 MULTITHREADED, PARALLEL, AND ASYNC PROGRAMMING
}
}
Opting in to a PLINQ Query
If you want to inform the TPL to execute this query in parallel (if possible), you will want to make use of
the AsParallel() extension method as so:
int[] modThreeIsZero = (from num in source.AsParallel() where num % 3 == 0
orderby num descending select num).ToArray();
Notice how the overall format of the LINQ query is identical to what you have seen in previous
chapters. However, by including a call to AsParallel(), the TPL will attempt to pass the workload off to
an available CPU.
Cancelling a PLINQ Query
It is also possible to use a CancellationTokenSource object to inform a PLINQ query to stop processing
under the correct conditions (typically due to user intervention). Declare a form-level
CancellationTokenSource object named cancelToken and implement the Click handler of the btnCancel
to call the Cancel() method on this object. Here is the relevant code update:
public partial class MainForm : Form
{
private CancellationTokenSource cancelToken = new CancellationTokenSource();
private void btnCancel_Click(object sender, EventArgs e)
{
cancelToken.Cancel();
}
...
}
Now, inform the PLINQ query that it should be on the lookout for an incoming cancellation