Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How a thread to update progressbar which in a main form 1

Status
Not open for further replies.

aurorahe

Programmer
Jun 25, 2004
2
US
I put a progressbar in the main form's status bar. My program needs to do a long calculation in a worker thread which should update the progressbar to show its progress.

Now i am trying to pass the main form to the thread, then call the "mainForm.statusBar.StatusProgressPerformStep();" from the worker thread. But it doesn't work sometime. What is the problem? What should be a right and efficient way to do such job?
 
should i use "BeginInvoke()" from main thread to do the progressbar updates?
 

Here is a ppatern when you need to pass data to a thread and retrieve data from a thread using a callback
1. Define a class that contains the data and the callback
Code:
using System;
using System.Threading;

public class MyThreadObj 
{
    // Data used in this thread.

    private System.Windows.Forms.Form form;
    // Delegate used to execute the callback method when the task is complete.
    private MyCallback callback;
    // Constructor
     public MyThreadObj(System.Windows.Forms.Form  frm, MyCallback callbackDelegate) 
        {
           form=frm;
           callback = callbackDelegate;
        }
    // The thread procedure performs the task to update the progess bar
    // and then invokes the callback delegate 
    public void ThreadProgressBarProc()
   {
	// Update Progess bar 
	if (callback != null)
	    callback(form);
    }
    // Delegate for the callback method.
    //
    public delegate void MyCallback(System.Windows.Forms.Form frm);

}
2. Now the main process, instantiate the above class and start the thread:
Code:
public class Form1 : System.Windows.Forms.Form
	{
	
	private void btnCalc_Click(object sender, System.EventArgs e)
	{
        // Supply the state information required by the task.
        MyThreadObj to = new MyThreadObj( this,  new MyCallback(EndCalculationCallback) );

        Thread t = new Thread(new ThreadStart(to.ThreadProgressBarProc));
        t.Start();
        //...
    }

    // The callback method must match the signature of the
    // callback delegate.
    //
    public static void EndCalculationCallback(System.Windows.Forms.Form form)
 {
        // Update the status bar in the main form 
        System.Windows.Forms.Form.MessageBox.Show("Calculation task finished );  
    }
}
-obislavu-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top