多线程进度条的简单使用,界面不卡顿。如下图:
简单源码如下:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace threadTest { /// <summary> /// 多线程测试-简单实例 /// </summary> public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnThread_Click(object sender, EventArgs e) { progressBar1.Value = 0; progressBar1.Maximum = 100; progressBar1.Minimum = 0; progressBar1.Step = 1; progressBar2.Value = 0; progressBar2.Maximum = 100; progressBar2.Minimum = 0; progressBar2.Step = 1; Task.Factory.StartNew(StartProcess1); Task.Factory.StartNew(StartProcess2); } private void StartProcess1() { for (int i = 0; i < 10000; i++) { //执行业务逻辑。
if (i % 100 == 0) { Invoke(new Action(viewProcess1)); Thread.Sleep(100); } } } private void viewProcess1() { progressBar1.Value += progressBar1.Step; //让进度条增加一次 lblProcess1.Text = progressBar1.Value.ToString() + "%"; } private void StartProcess2() { for (int i = 0; i < 10000; i++) { //执行业务逻辑。 if (i % 100 == 0) { Invoke(new Action(viewProcess2)); Thread.Sleep(100); } } } private void viewProcess2() { progressBar2.Value += progressBar2.Step ; lblProcess2.Text = progressBar2.Value.ToString() + "%"; } } }