Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*Seperate Class */
- //Delegate for your class to report the progress (this is necessary to pass information between threads)
- public Action<int> ReportProgressDelegate { get; set; }
- //Method to report the progress using the delegate
- private void ReportProgress(int percent)
- {
- if (ReportProgressDelegate != null)
- ReportProgressDelegate(percent);
- }
- //Some Loop within Separate Class that contains a counter
- //Call the report progress method with a percent value, basically this is where you update your progress in your class
- counter++;
- double doublecounter = counter;
- double numberofruns = ExperimentsToBeRun.Count;
- double percent = (doublecounter/numberofruns)*100;
- int percenttoreport = (int) percent;
- ReportProgress(percenttoreport);
- /*Forms App */
- //Add a background worker using the Toolbox in form designer: it is under components BackgroundWorker
- //Start the background worker in the form constructor
- public Form1()
- {
- InitializeComponent();
- //Tell Background worker that it should report progress
- backgroundWorker1.WorkerReportsProgress = true;
- //Subscribe background worker events of progress changed and runworkercompleted to new event handlers
- backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
- backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
- }
- // Work you want done goes here:
- private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
- {
- //Create an instance of the class you want to do your work for you
- MyClass sp = new Myclass();
- //Pass the delegate from the background worker to your class so that work done in that class will update the progress
- //appropriately if you call the ReportProgress(int percent) method in your class
- sp.ReportProgressDelegate = backgroundWorker1.ReportProgress;
- //Process Data or do whatever
- //sp.ProcessData();
- }
- //Hookup your progressbar to the progresschanged event backgroundWorker1.ProgressChanged that we subscribed earlier
- void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
- {
- // The progress percentage is a property of e
- progressBar1.Value = e.ProgressPercentage;
- }
- //Do things once worker is completed if you want
- void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
- {
- }
- private void button1_Click(object sender, EventArgs e)
- {
- //Start BackgroundWorker and the backgroundWorker1_doWork section of code will run
- backgroundWorker1.RunWorkerAsync();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement