最近碰见一个例子,Copy大文件或者网络访问的时候处理假死。 那就用多线程加个进度条(只显示运行,没有进度)来表示状态运行吧。好了,废话少说,上个例子。先看结果图:
程序说明:
点击Button,运行一个数据累加器,textBox显示每次运行的结果,ProgressBar表示运行的状态。
好了,直接贴代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;namespace Testpro
{public partial class Form1 : Form{BackgroundWorker work = new BackgroundWorker();public Form1(){InitializeComponent();work.WorkerReportsProgress = true;work.DoWork += Count;work.RunWorkerCompleted += completeRun;Control.CheckForIllegalCrossThreadCalls = false;this.textBox1.ScrollBars = ScrollBars.Both;}private void button1_Click(object sender, EventArgs e){this.progressBar1.Style = ProgressBarStyle.Marquee;work.RunWorkerAsync();}private void Count(object sender, DoWorkEventArgs e){ float num = 0.0f;int cun = 0;while (num < 5000){cun++;num += 4f; this.textBox1.Text += num.ToString() + "\t" + e.Result;if (cun == 9){textBox1.Text += Environment.NewLine;cun = 0;}} }public void SetText(object num){textBox1.Text += num.ToString() + "\n";}private void completeRun(object sender, RunWorkerCompletedEventArgs e){this.progressBar1.Style = ProgressBarStyle.Blocks;this.textBox1.Text += "complete";MessageBox.Show("Running complete.....");} }
}