C#多线程显示运行状态

Copy大文件或者网络访问的时候处理假死。 那就用多线程加个进度条(只显示运行,没有进度)来表示状态运行吧。好了,废话少说,上个例子。先看结果图:

imageimage

程序说明 代码生成器

点击Button,运行一个数据累加器,textBox显示每次运行的结果,ProgressBar表示运行的状态。

好了,直接贴代码:

01 using System;
02 using System.Collections.Generic;
03 using System.ComponentModel;
04 using System.Data;
05 using System.Drawing;
06 using System.Linq;
07 using System.Text;
08 using System.Windows.Forms;
09 using System.Threading;
10   
11 namespace Testpro
12
13     public partial class Form1 : Form
14     
15         BackgroundWorker work = new BackgroundWorker();
16         public Form1()
17         
18             InitializeComponent();
19             work.WorkerReportsProgress = true
20             work.DoWork += Count;
21             work.RunWorkerCompleted += completeRun;
22             Control.CheckForIllegalCrossThreadCalls = false
23             this.textBox1.ScrollBars = ScrollBars.Both;
24         
25   
26         private void button1_Click(object sender, EventArgs e)
27         
28             this.progressBar1.Style = ProgressBarStyle.Marquee;
29               
30             work.RunWorkerAsync();
31         
32   
33         private void Count(object sender, DoWorkEventArgs e)
34         {            
35             float num = 0.0f;
36             int cun = 0;
37             while (num < 5000)
38             
39                 cun++;
40                 num += 4f;              
41                this.textBox1.Text += num.ToString() + "\t" + e.Result;
42                if (cun == 9)
43                
44                    textBox1.Text += Environment.NewLine;
45                    cun = 0;
46                
47             }            
48         
49   
50         public  void SetText(object num)
51         
52             textBox1.Text += num.ToString() + "\n"
53         
54   
55         private void completeRun(object sender,  RunWorkerCompletedEventArgs e)
56         
57             this.progressBar1.Style = ProgressBarStyle.Blocks;
58               
59             this.textBox1.Text += "complete"
60             MessageBox.Show("Running complete.....");
61         }       
62     
63 }

猜你喜欢

转载自1175319258.iteye.com/blog/2158958