程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> WinForm多線程及委托防止界面假死,winform多線程

WinForm多線程及委托防止界面假死,winform多線程

編輯:C#入門知識

WinForm多線程及委托防止界面假死,winform多線程


當有大量數據需要計算、顯示在界面或者調用sleep函數時,容易導致界面卡死,可以采用多線程加委托的方法解決。

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 WindowsFormsApplication1
{
public partial class FormMain : Form
{
DataTable table;
int currentIndex = 0;
int max = 10000;
public FormMain()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
Thread thread = new Thread(new ThreadStart(LoadData));
thread.IsBackground = true;
thread.Start();

progressBar1.Minimum = 0;
progressBar1.Maximum = max;
}
private void LoadData()
{
SetLableText("數據加載中...");
currentIndex = 0;
table = new DataTable();
table.Columns.Add("id");
table.Columns.Add("name");
table.Columns.Add("age");
while (currentIndex < max)
{
SetLableText(string.Format("當前行:{0},剩余量:{1},完成比例:{2}%", currentIndex, max - currentIndex,
(Convert.ToDecimal(currentIndex) / Convert.ToDecimal(max) * 100).ToString("f0")));
SetPbValue(currentIndex);
DataRow dr = table.NewRow();
dr["id"] = currentIndex;
string name = "張三";
dr["name"] = name;
dr["age"] = currentIndex + 5;
table.Rows.Add(dr);
currentIndex++;
}
SetDgvDataSource(table);
SetLableText("數據加載完成!");

this.BeginInvoke(new MethodInvoker(delegate()
{
button1.Enabled = true;
}));
}
delegate void labDelegate(string str);
private void SetLableText(string str)
{
if (label1.InvokeRequired)
{
Invoke(new labDelegate(SetLableText), new string[] { str });
}
else
{
label1.Text = str;
}
}
delegate void dgvDelegate(DataTable table);
private void SetDgvDataSource(DataTable table)
{
if (dataGridView1.InvokeRequired)
{
Invoke(new dgvDelegate(SetDgvDataSource), new object[] { table });
}
else
{
dataGridView1.DataSource = table;
}
}
delegate void pbDelegate(int value);
private void SetPbValue(int value)
{
if (progressBar1.InvokeRequired)
{
Invoke(new pbDelegate(SetPbValue), new object[] { value });
}
else
{
progressBar1.Value = value;
}
}
}
}

運行效果圖:

}<br>運行效果圖:

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved