Reputation: 287
I have a process that takes a long time, and I want a window to show the progress. But, I can't figure how to display the progress.
Here's the code:
if (procced)
{
// the wpf windows :
myLectureFichierEnCour = new LectureFichierEnCour(_myTandemLTEclass);
myLectureFichierEnCour.Show();
bgw = new BackgroundWorker();
bgw.DoWork += startThreadProcessDataFromFileAndPutInDataSet;
bgw.RunWorkerCompleted += threadProcessDataFromFileAndPutInDataSetCompleted;
bgw.RunWorkerAsync();
}
And:
private void startThreadProcessDataFromFileAndPutInDataSet(object sender, DoWorkEventArgs e)
{
_myTandemLTEclass.processDataFromFileAndPutInDataSet(
_strCompositeKey,_strHourToSecondConversion,_strDateField);
}
I can call _myTandemLTEclass.processProgress
to get a hint of the progress.
Upvotes: 2
Views: 3193
Reputation:
Your backgroundWorker thread needs to handle the DoWork
method and ProgressChanged
.
You also need to make sure you turn on the WorkerReportsProgress
flag to true (off by default).
See example code:
private void downloadButton_Click(object sender, EventArgs e)
{
// Start the download operation in the background.
this.backgroundWorker1.RunWorkerAsync();
// Disable the button for the duration of the download.
this.downloadButton.Enabled = false;
// Once you have started the background thread you
// can exit the handler and the application will
// wait until the RunWorkerCompleted event is raised.
// Or if you want to do something else in the main thread,
// such as update a progress bar, you can do so in a loop
// while checking IsBusy to see if the background task is
// still running.
while (this.backgroundWorker1.IsBusy)
{
progressBar1.Increment(1);
// Keep UI messages moving, so the form remains
// responsive during the asynchronous operation.
Application.DoEvents();
}
}
Upvotes: 1
Reputation: 421988
You should handle the ProgressChanged
event and update the progress bar in your user interface there.
In the actual function that does the work (DoWork
event handler), you'll call the ReportProgress
method of the BackgroundWorker
instance with an argument specifying the amount of task completed.
The BackgroundWorker example in MSDN Library is a simple code snippet that does the job.
Upvotes: 6