I read documents about thread pooling and I wrote test code to load data into two grids from different threads. Sometimes, though, only one grid fills, and the other remains empty. And sometimes everything's ok. Why? when i use waitall i get this exception:WaitAll for multiple handles on a STA thread is not supported.
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();
}