BackgroundWorker 简单示例()
//异步使用前一定要把下面的代码进行初始化才能成功调用 //if (!bgwtemp.IsBusy) //{ //bgwtemp.RunWorkerAsync(); //} public BackgroundWorker bgwtemp = null; public Form2() { InitializeComponent(); bgwtemp = new BackgroundWorker(); bgwtemp.DoWork += bgwtemp_work; bgwtemp.RunWorkerCompleted += bgwtemp_RunWorkerCompleted; } private void bgwtemp_work(object sender, DoWorkEventArgs e) { ss(); } private void bgwtemp_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //MessageBox.Show("success"); } delegate void WriteLogEvent(string value); private void WriteLog(string value) { if (this.InvokeRequired) { WriteLogEvent w = new WriteLogEvent(WriteLog); this.Invoke(w, new object[] { value }); } else { try { richTextBox1.AppendText(DateTime.Now.ToString("HH:mm:ss") + " " + value + "\r\n"); richTextBox1.HideSelection = false; } catch (Exception ex) { } } } public void ss() { for (int i = 0; i < 6; i++) { //Thread.Sleep(1000); WriteLog(i.ToString()); } } private void Form2_Load(object sender, EventArgs e) { if (!bgwtemp.IsBusy) { bgwtemp.RunWorkerAsync(); } }