using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace AsynchronousAdoNet { public partial class Form1 : Form { public Form1() { InitializeComponent(); toolStripProgressBar1.Enabled = false; } public void BindDate() { //执行异步操作时,连接字符串中必须启用Asynchronous Processing string strConnection = "Data Source=.;Initial Catalog=AdventureWorks;" + "Integrated Security=True;Asynchronous Processing=True"; string strQuery = "SELECT ProductCategory_1.*, Production.ProductCategory.*" + "FROM Production.ProductCategory INNER JOIN " + "Production.ProductCategory AS ProductCategory_1 ON " + "Production.ProductCategory.ProductCategoryID = " + "ProductCategory_1.ProductCategoryID"; using (SqlConnection conn = new SqlConnection(strConnection)) { SqlCommand comm = new SqlCommand(strQuery, conn); IAsyncResult asyncResult = null;//表示异步操作的状态 try { conn.Open(); asyncResult = comm.BeginExecuteReader(CommandBehavior.CloseConnection); toolStripProgressBar1.Enabled = true; toolStripStatusLabel1.Text = "Processing"; while (!asyncResult.IsCompleted)//判断异步操作是否完成 { //Maximun = 100,Minimun = 0,Step = 10,Style = Blocks if (toolStripProgressBar1.Value == toolStripProgressBar1.Maximum) toolStripProgressBar1.Value = toolStripProgressBar1.Minimum; toolStripProgressBar1.PerformStep(); } SqlDataReader reader = comm.EndExecuteReader(asyncResult); DataTable dtResult = new DataTable(); dtResult.Load(reader); if (dtResult != null) dataGridView1.DataSource = dtResult; //设置进度条,文字 toolStripProgressBar1.Value = toolStripProgressBar1.Maximum; toolStripProgressBar1.Enabled = false; toolStripStatusLabel1.Text = "Completed"; } catch(Exception e) { MessageBox.Show(e.Message); } } } private void btnGetDate_Click(object sender, EventArgs e) { BindDate(); } } }