Reference: http://www.cnblogs.com/xpvincent/archive/2013/08/19/3268001.html
When there is a large amount of data to calculate, display in the interface or call the sleep function, it is easy to cause the interface to die, can use multi-line loads delegate method to solve;
usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Threading;namespacewindowsformsapplication3{ Public Partial classform1:form {DataTable table; intCurrentindex =0; intMax =10000; PublicForm1 () {InitializeComponent (); } Private voidButton1_Click (Objectsender, EventArgs e) {buttonok.enabled=false; Thread Thread=NewThread (NewThreadStart (LoadData)); Thread. IsBackground=true; Thread. Start (); Progressbar1.minimum=0; Progressbar1.maximum=Max; } Private voidLoadData () {Setlabeltext ("Data Loading ..."); Currentindex=0; Table=NewDataTable (); Table. Columns.Add ("ID"); Table. Columns.Add ("name"); Table. Columns.Add (" Age"); while(Currentindex <max) {Setlabeltext (string. Format ("Current line: {0}, amount remaining: {1}, Completion scale: {2}%", Currentindex, Max-Currentindex, (Convert.todecimal (currentindex)/Convert.todecimal (max) * -). ToString ())); Setpbvalue (Currentindex); DataRow Dr=table. NewRow (); dr["ID"] =Currentindex; dr["name"] ="Zhang San"; dr[" Age"] = Currentindex +5; Table. Rows.Add (DR); Currentindex++; } setdgvdatasource (table); Setlabeltext ("Data Loading Complete"); This. BeginInvoke (NewMethodInvoker (Delegate() {buttonok.enabled=true; })); } Delegate voidLabdelegate (stringstr); Private voidSetlabeltext (stringstr) { if(textbox1.invokerequired) {Invoke (NewLabdelegate (Setlabeltext),New string[] {str}); } Else{TextBox1.Text=str; } } Delegate voiddgvdelegate (DataTable table); Private voidSetdgvdatasource (DataTable table) {if(datagridview1.invokerequired) {Invoke (NewDgvdelegate (Setdgvdatasource),New Object[] {table}); } Else{Datagridview1.datasource=table; } } Private Delegate voidPbdelegate (intvalue); Private voidSetpbvalue (intvalue) { if(progressbar1.invokerequired) {Invoke (NewPbdelegate (Setpbvalue),New Object[] {value}); } Else{progressBar1.Value=value; } } }}
Full demo Download
WinForm Multithreading + Delegation to prevent the screen from suspended animation