how to use Progress bar in backgroundworker
-
Saturday, May 05, 2012 11:22 AMHi Friends....
I am stuck with BackGroundWorker. I learn Three basic steps to do work with Background worker.
Step 1 :- DoWork Event -- In this we do our work. i.e. Call Methods, Function, execute Querys' etc. and also enables background Properties like WorkerReportsProgress
, WorkerSupportsCancellation etc.
Step 2: ProgressChanged event : This is used to increment Progressbar value,and enable's access forms controls.
Step 3 : RunWorkerCompleted Event : It tells Work is completed or not .
But my problem is how to calculate max value for Progress Bar, how to increment Progress bar , because i have to call different methods some will retrieve values from Database, some will do work within the application. I changed style to Marque and set MarqueeAnimationSpeed but due to lot of Processing it hides the Progressbar.
If i put all methods in one Method then call that method in DoWork Event then it hides Progressbar. and shows it after doing all work.
If I call the part which take lot of time in DoWork event. by Calling method BackgrounfWorker.RunWorkerAsync() on btn_Click event then before going to DoWork Event it is executting lines bellow this method after executting all these then it is executting RunWorkAsync() method.
Please help me how to solve this Problem.
All Replies
-
Saturday, May 05, 2012 11:35 AMWhat do you mean with "it hides the ProgressBar"? You may take a look at Rudy's example.
-
Saturday, May 05, 2012 1:08 PM
Check here in this simple example:
public partial class Form1 : Form { BackgroundWorker bgw = new BackgroundWorker(); public Form1() { InitializeComponent(); label1.Text = ""; label2.Text = ""; } private void button1_Click_1(object sender, EventArgs e) { bgw.DoWork += new DoWorkEventHandler(bgw_DoWork); bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged); bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted); bgw.WorkerReportsProgress = true; bgw.RunWorkerAsync(); } void bgw_DoWork(object sender, DoWorkEventArgs e) { int total = 57; //some number (this is your variable to change)!! for (int i = 0; i <= total; i++) //some number (total) { System.Threading.Thread.Sleep(100); int percents = (i * 100) / total; bgw.ReportProgress(percents, i); //2 arguments: //1. procenteges (from 0 t0 100) - i do a calcumation //2. some current value! } } void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; label1.Text = String.Format("Progress: {0} %", e.ProgressPercentage); label2.Text = String.Format("Total items transfered: {0}", e.UserState); } void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { //do the code when bgv completes its work } }
Mitja
-
Saturday, May 05, 2012 3:59 PMModerator
What do you mean with "it hides the ProgressBar"? You may take a look at Rudy's example.
I think someone took that example at the link, dumbed it down a bit to make less code, and put it into the MSDN Library under VS2010. It contains examples in 3 languages.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker(v=vs.90).aspx VS2008 (original posts and complaints)
http://msdn.microsoft.com/en-US/library/8xs8549b(v=vs.100).aspx VS2010 (notice date of feedback comment at bottom)
I had complained that the Fibonacci example is way too complex if you do not understand the math. So, they added a second, simpler example to the VS2010 library. The first example is nearly identical to my sample.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx VS2010 (notice date of ChangeHistory at bottom)
It even uses the label to display percentage!
Rudy =8^D
Mark the best replies as answers. "Fooling computers since 1971."
http://thesharpercoder.blogspot.com/
- Edited by Rudedog2MVP, Moderator Saturday, May 05, 2012 4:08 PM
-
Saturday, May 05, 2012 4:07 PMModerator
Post your DoWork event to give us some idea of what you are doing? The only reason that I can think of for the ProgressBar to "hide" would be if the time consuming code is executing on the main thread, instead of a worker thread.
Rudy =8^D
Mark the best replies as answers. "Fooling computers since 1971."
-
Sunday, May 06, 2012 4:07 AM
Hi Rai007
in order to handling the ProgressChanged event , you must raise the event by calling the ReportProgress method in the DoWork Event handler
and you must compute the max progress step value before the loop statement.
and then you then BackgroundWorker.ReportProgress(int) Method to report the executing progress.
have a nice day.
DON'T TRY SO HARD,THE BEST THINGS COME WHEN YOU LEAST EXPECT THEM TO.
-
Monday, May 07, 2012 11:47 AM
Sorry Friends.... Not replied after posting question. Because it was off in office on Sunday.
My all Codes are below as it was asked by Rudedog2
On btnStart_Click I have set Progressbar1.Style= ProgressBarStytle.Marque and started Marque. (Because in so many methods i am unable to get
total time required to fill.) after this i have called backGroundWorker1.RunWorkerAsync(100); but control is executing
this.dtg.DataSource = this.RetrevingValue().Tables[0];
before Do Work Event and hiding Progressbar1 and showing it back after doing all works.
BtnStart_Click event
private void btnStart_Click(object sender, EventArgs e) { progressBar1.Style = ProgressBarStyle.Marquee; progressBar1.MarqueeAnimationSpeed = 10; dtg.Columns.Clear(); dtg.Columns.Add("SrNo", "SrNo"); dtg.Columns["SrNo"].Visible = false; backgroundWorker1.RunWorkerAsync(100); this.dtg.DataSource = this.RetrevingValue().Tables[0]; this.FormattingDtg(); }
BackGroundWorker1_DoWork event
Thread.Sleep(Convert.ToInt32(e.Argument)); e.Result = InsertingValuesInTbTempSaleReport("salesummaryBillWise11", textBox1.Text, textBox2.Text);BackGroundWorker1_RunWorkCompleted event
if ((bool ) e.Result) progressBar1.MarqueeAnimationSpeed =0;Inserting Values Method
bool InsertingValuesInTbTempSaleReport(string ProcedureName , string FromDate , string ToDate ) { try { using (SqlConnection Con = ConnectionOpen()) { string Qry = "" + ProcedureName + ""; SqlCommand Com = new SqlCommand(Qry, Con); Com.CommandTimeout = 100; Com.CommandType = CommandType.StoredProcedure; Com.Parameters.AddWithValue ("@fromDate", Convert.ToDateTime(FromDate)); Com.Parameters.AddWithValue("@toDate", Convert.ToDateTime(ToDate)); Com.Parameters.AddWithValue("@UniqueId", "BFEBFBFF-American-ASUSTeK "); DataSet Ds = new DataSet(); SqlDataAdapter Adapter = new SqlDataAdapter(Com); Adapter.Fill(Ds); return true; } } catch (Exception ex) { throw new Exception(ex.Message); } }
Retreving Value MethodDataSet RetrevingValue() { using (SqlConnection con = ConnectionOpen()) { DataSet ds = new DataSet(); string Qry = "Select * from tbtempSalereport1"; SqlCommand com = new SqlCommand(Qry, con); com.CommandType = System.Data.CommandType.Text; SqlDataAdapter Adapter = new SqlDataAdapter(com); Adapter.Fill(ds ); return ds; } }
Formatting DatagridView (Dtg) Methodvoid FormattingDtg() { dtg.Columns[0].Width = 150; dtg.Rows[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dtg.Rows[4].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dtg.Rows[6].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; dtg.Columns["SrNo"].Visible = true; dtg.Columns["SrNo"].DisplayIndex = 0; }
-
Monday, May 07, 2012 11:54 AM
-
Monday, May 07, 2012 1:43 PM
Your code is backwards. DoWork in the DoWork event. Update the UI in the RunWorkerCompleted event. There are many examples of how to use the BackgroundWorker on the web. I suggest you follow Rudy's example, since he has responded to this thread.
-
Tuesday, May 08, 2012 9:33 AM
Hi Rai007,
I got your problem, the simple and best solution for this is, set your Progress Bar Style property to Marquee, That's is it resembles still work is going on... once done raises the RunWorkerCompleted Event where you can show a message.
Sai Kumar K http://www.santoshtechnologies.com http://saimaterial.wordpress.com
- Proposed As Answer by Sai Kumar Koona Tuesday, May 08, 2012 9:47 AM
- Unproposed As Answer by Rudedog2MVP, Moderator Tuesday, May 08, 2012 1:53 PM
-
Tuesday, May 08, 2012 12:15 PMI have done same but some times when there is large number of rows then it stops the marque and change the form to not responding state.
-
Tuesday, May 08, 2012 12:18 PM
I have done same but some times when there is large number of rows then it stops the marque and change the form to not responding state.
Post your new code. -
Tuesday, May 08, 2012 12:38 PMTry to raise Progress Changed Event @ regular time, so that the form main thread gets calling... in this case form will be in responding state...
Sai Kumar K http://www.santoshtechnologies.com http://saimaterial.wordpress.com
- Edited by Sai Kumar Koona Tuesday, May 08, 2012 12:39 PM
-
Tuesday, May 08, 2012 1:11 PM
Hi ...... @Sai Kumar Koona
i have insert all values at do work event
and Retrieved data and Formatted datagridView in ProgressChangeEvent
so I can't call Progresschange event again and again.
Now As i have told you, in current situation it is taking less time in DoWork Event but taking lot of type while Formatting in case when there is large amount of rows.
Can i use new threads for formatting Datgridview if Yes then how?.
-
Friday, May 11, 2012 6:14 AMModerator
Hi,
Could you please post the latest sample codes here for us to do further investigation?
Have a nice weekend!
Thanks
Michael Sun [MSFT]
MSDN Community Support | Feedback to us
-
Tuesday, May 15, 2012 9:41 AM
Looking at the code you posted earlier in the thread, I would remove the try..catch block from the InsertingValuesInTbTempSaleReport then in your DoWork event have code as follows:
try { Thread.Sleep(Convert.ToInt32(e.Argument)); e.Result = InsertingValuesInTbTempSaleReport("salesummaryBillWise11", textBox1.Text, textBox2.Text); } catch (Exception ex) { e.Result = ex; }
Then in your RunWorkerCompletedEvent, check if e.Result is an object of type Exception and display an error message here or update your GUI if no exception occurred.
- Proposed As Answer by Michael Sun [MSFT]Microsoft Employee, Moderator Thursday, May 17, 2012 6:12 AM

