多線程進度條的簡單使用,界面不卡頓。如下圖:
簡單源碼如下:
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() + "%"; } } }