This article mainly introduces C # to obtain data from the database and asynchronously update the UI method, we refer to the use of the bar
Read the database asynchronously, and there is a problem with the data binding, that is, the form interface cannot be closed, and the task is closed to end the process. For example, the following code sets the thread update UI A2 first, in the usual way. Checkforillegalcrossthreadcalls = false; //a2 for Form name The following code is to obtain data from the database and bind code as follows: private void Button1_Click (object sender, EventArgs e) &nbs P SqlConnection con; &NB Sp SqlCommand com; try { &NBS P con = new SqlConnection ("UID=SA; Password=123;initial Catalog=ad;data source=192.168.1.1; Asynchronous Processing=true "); con. Open (); COM = new SqlCommand ("SELECT top * from Tb_user", con); COM. Beginexecutereader (New AsyncCallback (Deldatabin), COM);   } catch (Exception ex) { MessageBox.Show ("program error, message: + ex.") message); privat e void Deldatabin (IAsyncResult ar) { if (AR. iscompleted) { Sqlcomman d com = (SqlCommand) ar. asyncstate; SqlDataReader dr = com. Endexecutereader (AR); DataTable dt = new DataTable (); DT. Load (DR); Dr. Close (); THIs.dataGridView1.DataSource = DT; //binding Data &N Bsp } to complete the binding work here, run to see the effect, in fact, this is the phenomenon of the form of suspended animation. below by invoke to implement first declare the delegate public delegate void Updatedg (DataTable dt); then databin to bind DataGridView code as follows: public void Databin (DataTable dt) { , Datagridview1.datasource = dt &NBS P return; } on-line call the following method code as follows://Binding Data &NBS P if (this. invokerequired) UPDATEDG ur = new UPDATEDG (databin); this. Invoke (Ur,DT); The complete code is as follows: code: private void button1_click (object sender, EventArgs e) { &N Bsp SqlConnection con; SqlCommand com; try { &NBS P con = new SqlConnection ("UID=SA; Password=123;initial Catalog=ad;data source=192.168.1.1; Asynchronous Processing=true "); con. Open (); COM = new SqlCommand ("SELECT top * from Tb_user", con); COM. Beginexecutereader (New AsyncCallback (Deldatabin), COM); CatCH (Exception ex) { Mess Agebox.show ("program error, message: + ex.") message); privat e void Deldatabin (IAsyncResult ar) { if (AR. iscompleted) { Sqlcomman d com = (SqlCommand) ar. asyncstate; SqlDataReader dr = com. Endexecutereader (AR); DataTable dt = new DataTable (); DT. Load (DR); Dr. Close (); //this.datagridview1.datasource = dt;//bound data &NBSP if (this. invokerequired) UPDATEDG ur = new UPDATEDG (databin); this. Invoke (Ur, dt); } } public delegate void Updatedg (DataTable dt); public void Databin (DataTable dt) { &N Bsp Datagridview1.datasource = DT; return; } Check run look, you'll find out.