78. Parallel Monte Carlo π

This example solution uses the same approach used by the preceding solution. It uses form-level variables to pass information to the parallel instances of a method. Those instances perform calculations and then use locking to save their results to the form-level variables.

The following code shows the form-level variables:

private int NumHits = 0;private object LockObject = new object();private int MonteCarloWidth = 0, MonteCarloHeight = 0;private Bitmap MonteCarloBitmap = null;private const int PointsPerCall = 10000;

The following method starts the parallel execution:

// Use Monte Carlo simulation to estimate pi.private double MonteCarloPi(int numPoints){    // Make a bitmap to show points. MonteCarloWidth = pointsPictureBox.ClientSize.Width; ...

Get The Modern C# Challenge now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.