我读了关于线程池的文档,并且我写了测试代码来将数据加载到来自不同线程的两个网格中。但是,有时候,只有一个网格填充,而另一个网格是空的。有时候一切正常。为什么? 当我使用waitall我得到这个异常:不支持WAA线程上的多个句柄的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();
}
此代码是否在Web应用程序中? – Dinesh
没有它的胜利应用程序。 – heavy
您是否试图理解这个理论,或者这是否意图成为实际的生产代码?虽然可以通过这种方式同时执行SQL Server命令,但绝对不是推荐的方法。你在使用.NET 4.5吗? – RickNZ