/// <summary> /// The calculate/cancel button event /// </summary> /// <param name="sender">Reference to the object that raised the event</param> /// <param name="e">Provides data for a cancelable event</param> private void _calcButton_Click(object sender, EventArgs e) { if (this._calcButton.Text == "Calculate") { timer1.Start(); // Just a simple object to hold some values to be accessed globally pi = new PiObject { calcValue = "", digits = (int)_digits.Value, progress = 0 }; backgroundWorker1.RunWorkerAsync(pi); progressBar1.Maximum = pi.digits; _calcButton.Text = "Cancel"; } else { timer1.Stop(); backgroundWorker1.CancelAsync(); _calcButton.Text = "Calculate"; } }
/// <summary> /// Our main worker thread. This is the main loop that calculates Pi /// </summary> /// <param name="sender">Reference to the object that raised the event</param> /// <param name="e">Provides data for a cancelable event</param> private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { PiObject piObj = e.Argument as PiObject; BackgroundWorker bw = sender as BackgroundWorker; StringBuilder pi = new StringBuilder("3", piObj.digits + 2); if (piObj.digits > 0) { pi.Append("."); for (int i = 0; i < piObj.digits; i += 9) { if (!this.backgroundWorker1.CancellationPending) { int nineDigits = NineDigitsofPi.StartingAt(i + 1); int digitCount = Math.Min(piObj.digits - i, 9); String ds = String.Format("{0:D9}", nineDigits); pi.Append(ds.Substring(0, digitCount)); piObj.calcValue = pi.ToString(); piObj.progress = i + 1; } else { e.Cancel = true; } } } }