വെള്ളിയാഴ്‌ച, ഒക്‌ടോബർ 5

How to use background worker with Progress Bar based on user state in C#

How to use background worker with Progress Bar based on user state in C#


//Intializing New Progress Bar
var NCPB = new NewCustomisedProgressBar();


//Creating new Background Worker 
var bgworker = new BackgroundWorker();

//Setting Background Worker for reporting progress
bgworker.WorkerReportsProgress = true;

//Do The Main Work here in Background Thread

bgworker.DoWork += delegate(object sender1, DoWorkEventArgs e1)  
{
//Write the working code here
//Remember GUI Triggering codes cant be written inside this
//for that use Report Progress Funtion
//Here I am triggering gui 5 times to make change in progress bar value after each task completion

//First Time GUI Trigger,setting progress bar value to 0
(sender1 as BackgroundWorker).ReportProgress(0, 0);
//Do The First Quarter Work Here


//Second Time GUI Trigger,setting progress bar value to 25
(sender1 as BackgroundWorker).ReportProgress(0, 1);
//Do The Second Quarter Work Here
//Third Time GUI Trigger,setting progress bar value to 50
(sender1 as BackgroundWorker).ReportProgress(0, 2);
//Do The Third Quarter Work Here


//Fourth Time GUI Trigger,setting progress bar value to 75
(sender1 as BackgroundWorker).ReportProgress(0, 3);
//Do The Fourth Quarter Work Here

//Update Progress Bar value to 100
(sender1 as BackgroundWorker).ReportProgress(0, 4);
};

//Reflect The changes in progress bar and other elements in UI Thread  

bgworker.ProgressChanged += delegate(object sender2,ProgressChangedEventArgse2)
 {

if (e2.UserState != null)
switch (Convert.ToInt32(e2.UserState.ToString()))
   {

case 0:
NCPB.ProgressValue =0;
//Can Do Other GUI Tasks Here
break;

case 1:
NCPB.ProgressValue =25;
//Can Do Other GUI Tasks Here
break;

case 2:
NCPB.ProgressValue =50;
//Can Do Other GUI Tasks Here
break;

case 3:
NCPB.ProgressValue =75;
//Can Do Other GUI Tasks Here
break;

case 4:
NCPB.ProgressValue =100;
//Can Do Other GUI Tasks Here
break;

}
};

/Close Progress Bar when work complete
bgworker.RunWorkerCompleted += delegate(object sender3, RunWorkerCompletedEventArgs e3)   {  
   NCPB.Close();
   };