📄 asynccalcpiform.cs
字号:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace MySecondApp {
public partial class AsyncCalcPiForm : Form {
public AsyncCalcPiForm() {
InitializeComponent();
}
private void calcButton_Click(object sender, EventArgs e) {
// Set UI state
this.calcButton.Enabled = false;
int digits = (int)this.decimalPlacesNumericUpDown.Value;
this.resultsTextBox.Text = "";
this.calcToolStripStatusLabel.Text = "Calculating...";
this.calcToolStripProgressBar.Visible = true;
// Initiate asynchronous worker thread
this.backgroundWorker.RunWorkerAsync(digits);
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) {
// This method will run on a thread other than the UI thread.
// Be sure not to manipulate any Windows Forms controls created
// on the UI thread from this method.
// Get number of digits to calculate pi to
int digits = int.Parse(e.Argument.ToString());
StringBuilder pi = new StringBuilder("3", digits + 2);
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
// Report initial progress
worker.ReportProgress(0, pi.ToString());
// Calculate rest of pi, if required
if( digits > 0 ) {
pi.Append(".");
for( int i = 0; i < digits; i += 9 ) {
// Calculate next i decimal places
int nineDigits = NineDigitsOfPi.StartingAt(i + 1);
int digitCount = Math.Min(digits - i, 9);
string ds = string.Format("{0:D9}", nineDigits);
pi.Append(ds.Substring(0, digitCount));
// Report current progress
int digitsSoFar = i + digitCount;
float progressPercentage = (float)digitsSoFar / (float)digits * 100;
worker.ReportProgress((int)progressPercentage, pi.ToString());
}
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e) {
// Executing on the UI thread
string pi = (string)e.UserState;
this.calcToolStripProgressBar.Value = e.ProgressPercentage;
this.resultsTextBox.Text = pi;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
// Reset progress status strip
this.calcButton.Enabled = true;
this.calcToolStripStatusLabel.Text = "Ready";
this.calcToolStripProgressBar.Visible = false;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -