Intro
Hi. It is Brigh777 and today I will show you how to use such component as backgroundworker in your C++ application. First of all, I tell you why we need, such component, as backgroundworker. Backgroundworker is a really good thing then you want to run some background processes in your application. The standard application does all calculations, commands and other things in one thread. It causes a lot of problems, such as a long time of work, the main window of your program can hangs , while you program will do calculations. Another reason of doing that is to make some background process (like “demons” in Linux), which will work as long as the program does.
So let’s get started. By the way, I am explaining this topic on MS Visual Studio 2012. So, don’t panic :)
Creating
- First of all, you need to make a new C++ Windows Forms project. When you have done it, place the controls like in the window below:
- Then you need to choose a backgroundworker component from the list of tools and simply drag it on your form.
- After that modify the event of “Start” button by double clicking on it and writing the code below.
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
backgroundWorker1->RunWorkerAsync(1); //starting background worker
}
- The same for the “Cancel” button:
private: System::Void button2_Click(System::Object^ sender, System::EventArgs^ e) {
backgroundWorker1->CancelAsync(); //cancel backgroundworker
}
- Then it is done, you need to review the settings of backgroundwarker component.
Modifying Properties tab
Your properties should be like that:
Modifying Events tab:
- Double click near the event DoWork. It will do a new function. Write in it the code below:
private: System::Void backgroundWorker1_DoWork(System::Object^ sender, System::ComponentModel::DoWorkEventArgs^ e) {
while(true)
{
if(backgroundWorker1->CancellationPending) //if it was cancelled
{
e->Cancel=true;
break;
}
if(progressBar1->Value==progressBar1->Maximum) //if the progress bar value reached maximum
{
break;
}
backgroundWorker1->ReportProgress(10); //reporting progress
Thread::Sleep(1000); //wait for 1 second
}
}
To use Thread::Sleep() you need to add System::Threading namespace to your program.
- 2) Modify ProgressChanged event in the same they:
private: System::Void backgroundWorker1_ProgressChanged(System::Object^ sender, System::ComponentModel::ProgressChangedEventArgs^ e) {
progressBar1->Value+=e->ProgressPercentage; //rising the progressbar's value
}
- And the last RunWorker complete event:
private: System::Void backgroundWorker1_RunWorkerCompleted(System::Object^ sender, System::ComponentModel::RunWorkerCompletedEventArgs^ e) {
progressBar1->Value=0; //reseting value
if(e->Cancelled) //Messages for the events
{
MessageBox::Show("You have cancelled background worker!!!");
}
else
{
MessageBox::Show("Work completed!!");
}
}
Results:
- Running program:
- Message when work is done:
- Message when work is cancelled: