Reputation: 71
I am newbie and i learned alot of things from StackOverflow. I recently started using threading in my windows application. As far as i heard multi-threading makes things easy, like doing alot of event at the same time.
I have Stored procedures in SQL and I call then in few methods.
here is my code
private void EditCustomer_Load(object sender, EventArgs e)
{
screenszize_Location();
Thread BackgroundThread = new Thread
(
new ThreadStart(() =>
{
GridCustomerList.BeginInvoke(
new Action(() =>
{
LoadGrid();
}
));
}
));
BackgroundThread.Start();
Thread BackgroundThread1 = new Thread
(
new ThreadStart(() =>
{
ComboBxVechicleNumber.BeginInvoke(
new Action(() =>
{
LoadVnum();
}
));
}
));
BackgroundThread1.Start();
Thread BackgroundThread2 = new Thread
(
new ThreadStart(() =>
{
ComboBxBikeMake.BeginInvoke(
new Action(() =>
{
loadBikeMake();
}
));
}
));
BackgroundThread2.Start();
}
What this does is, * Screen Layout * Loads a 3 column Grid wit some 2000 rows * Loads Vehicle numbers from SQL table into a Combobox. * Loads Bike Names from SQL table into a Combobox.
My Computer is fast has best performance, but still The Form which i load freezes and becomes WHITE for couple of seconds and then a loads.
Am I doing the whole threading thing wrong ?
Upvotes: -1
Views: 96
Reputation: 71
Thanks to @mrlucmorin and Drik and TomTom and Every1
Hea is My Code Again.
private void LoadGrid()
{
Thread BackgroundThread = new Thread
(
new ThreadStart(() =>
{
ConnectionStringSettings consetting = ConfigurationManager.ConnectionStrings["AutoDB"];
String ConnectionString = consetting.ConnectionString;
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
int i = 0;
con.Open();
command.Connection = con;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "LoadAllCustomers";
da.SelectCommand = command;
da.Fill(ds, "dbo.TblCustomers");
GridCustomerList.BeginInvoke(
new Action(() =>
{
GridCustomerList.DataSource = ds.Tables["dbo.TblCustomers"];
}
));
}
));
BackgroundThread.Start();
}
It works Perfectly as expected :)
Upvotes: -1
Reputation: 5380
You don't show your LoadGrid method definition, but I guess it fetches data from the DB, and then sets the DataSource on a DataGridView or BindingSource.
You should split those 2 steps such that only the setting of the DataSource is done on the UI thread, and the fetching of the data still happens in the BackgroundThread.
Something like this:
Thread BackgroundThread = new Thread
(
new ThreadStart(() =>
{
//Fetch data here
GridCustomerList.BeginInvoke(
new Action(() =>
{
//Set DataSource here
}
));
}
));
Cheers
Upvotes: 1