我阅读了有关线程池的文档,并编写了测试代码以将来自不同线程的数据加载到两个网格中。但有时,只有一个网格填充,而另一个保持为空。有时一切都很好。为什么?当我使用 waitall 时出现此异常:不支持 STA 线程上的多个句柄的 WaitAll。
private void button1_Click(object sender, EventArgs e)
{
ManualResetEvent[] mre = new ManualResetEvent[2];
mre[0] = new ManualResetEvent(false);
multhread ml = new multhread(mre[0]);
ThreadPool.QueueUserWorkItem(ml.setdatabase,1);
mre[1] = new ManualResetEvent(false);
// multhread ml2 = new multhread(mre[1]);
ThreadPool.QueueUserWorkItem(ml.setdatabase2, 2);
WaitHandle.WaitAll(mre);
dataGridView1.DataSource = ml.propdt;
dataGridView2.DataSource = ml.propdt2;
}
public DataTable propdt2 { get; set; }
public void s()
{
string constring = "DATA SOURCE=.; database=test;integrated security= true; USER ID=sa;password=123456789";
SqlCommand com = new SqlCommand();
SqlConnection con = new SqlConnection(constring);
com.Connection = con;
com.CommandText = " select * from imgtable";
SqlDataAdapter adapt = new SqlDataAdapter(com);
DataTable dt2 = new DataTable();
adapt.Fill(dt2);
propdt2 = dt2;
}
}
public class multhread
{
private ManualResetEvent _doneEvent;
public multhread(ManualResetEvent doevent)
{
_doneEvent = doevent;
}
public static DataTable dt;
public static DataTable dt2;
public DataTable propdt { get; set; }
public DataTable propdt2 { get; set; }
public void setdatabase(Object threadContext)
{
string constring = "DATA SOURCE=.; database=test;integrated security= true; USER ID=sa;password=123456789";
SqlCommand com = new SqlCommand();
SqlConnection con = new SqlConnection(constring);
com.Connection = con;
com.CommandText = " select * from imgtable";
SqlDataAdapter adapt = new SqlDataAdapter(com);
dt2 = new DataTable();
adapt.Fill(dt2);
propdt2 = dt2;
_doneEvent.Set();
// return dt2;
}
public void setdatabase2(Object threadContext)
{
string constring = "DATA SOURCE=.; database=test;integrated security= true; USER ID=sa;password=123456789";
SqlCommand com = new SqlCommand();
SqlConnection con = new SqlConnection(constring);
com.Connection = con;
com.CommandText = " select * from imgtable order by id desc ";
SqlDataAdapter adapt = new SqlDataAdapter(com);
dt = new DataTable();
adapt.Fill(dt);
propdt = dt;
_doneEvent.Set();
}