使用ThreadPool来实现线程的复用
代码
1 protected override void OnLoad(EventArgs e)
2 {
3 base.OnLoad(e);
4
5 //1.同步读取数据
6 //GetCustomers();
7
8 //2.异步读取数据
9 BackgroundWorker worker = new BackgroundWorker();
10 //picLoading.Visible = true;
11 IsBusy = true;
12 worker.DoWork += (obj, arg) =>
13 {
14 arg.Result = GetCustomers();
15 };
16 worker.RunWorkerCompleted += (obj, arg) =>
17 {
18 BindingSource bs = new BindingSource(arg.Result, null);
19 lstCustomers.DataSource = bs;
20 lstCustomers.DisplayMember = "CompanyName";
21 lstCustomers.ValueMember = "CustomerID";
22
23 IsBusy = false;
24 //picLoading.Visible = false;
25 };
26 worker.RunWorkerAsync();
27
28 }
29
30 private bool IsBusy
31 {
32 set
33 {
34 picLoading.Visible = value;
35 }
36 }
代码
private List<CustomerInfo> GetCustomers()
{
List<CustomerInfo> result = new List<CustomerInfo>();
using (SqlConnection conn = new SqlConnection(connectionString))
{
Thread.Sleep(5000);
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT CustomerID,CompanyName FROM Customers";
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
result.Add(
new CustomerInfo()
{
CustomerID = reader.GetString(0),
CompanyName = reader.GetString(1)
});
}
reader.Close();
conn.Close();
}
}
return result;
}
public class CustomerInfo
{
public string CustomerID { get; set; }
public string CompanyName { get; set; }
}
private void lstCustomers_SelectedIndexChanged(object sender, EventArgs e)
{
if (lstCustomers.SelectedIndex != -1)
{
var customerId = ((CustomerInfo)lstCustomers.SelectedItem).CustomerID;
//picLoading.Visible = true;
IsBusy = true;
//3.使用ThreadPool(线程池)来实现线程的复用
ThreadPool.QueueUserWorkItem((obj) =>
{
var orders = GetOrderByCustomerID(customerId);
this.BeginInvoke(new Action(() =>
{
dgvOrders.DataSource = orders.Tables[0];
//picLoading.Visible = false;
IsBusy = false;
}));
});
}
}