WinForm multithreading and delegation prevent UI spoofing and winform Multithreading
When a large amount of data needs to be calculated, displayed on the interface, or the sleep function is called, it is easy to cause the interface to die. You can use multiple threads and delegation to solve this problem.
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 button#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 ("loading data ...");
CurrentIndex = 0;
Table = new DataTable ();
Table. Columns. Add ("id ");
Table. Columns. Add ("name ");
Table. Columns. Add ("age ");
While (currentIndex <max)
{
SetLableText (string. Format ("current row: {0}, remaining amount: {1}, completion ratio: {2} %", currentIndex, max-currentIndex,
(Convert. ToDecimal (currentIndex)/Convert. ToDecimal (max) * 100). ToString ("f0 ")));
SetPbValue (currentIndex );
DataRow dr = table. NewRow ();
Dr ["id"] = currentIndex;
String name = "zhangsan ";
Dr ["name"] = name;
Dr ["age"] = currentIndex + 5;
Table. Rows. Add (dr );
CurrentIndex ++;
}
SetDgvDataSource (table );
SetLableText ("Data Loading completed! ");
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 (maid)
{
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;
}
}
}
}
Run:
} <Br> run: