Click here to Skip to main content
Click here to Skip to main content

Background Task Dialog

By , 19 Apr 2004
 

Sample screenshot

Introduction

Hi, my name is Mauro H. Leggieri, a Windows and Game programmer. I made a little thing that may be useful, and want to share with you.

I wrote a class named CBackgroundTaskDialog derived from the standard CDialog class. It is a wrapper for dialog boxes where you must do a long-time process, optionally showing the progress information, but you don't want your application to appear to be hung.

Using the code

The code simply creates a background thread and calls some member functions where you write your own code and have some members to control when to start/stop the background process.

To use the code in your project, first add the BackgroundTaskDialog.cpp and BackgroundTaskDialog.h files to your project.

Then, in the header file of the dialog you want to subclass, add the include "BackgroundTaskDialog.h" statement and replace all CDialog words with CBackgroundTaskDialog and add the following member declarations to the class:

class your_dialog_class : public CBackgroundTaskDialog
{
  // Class definition an so on...
  // Code that you must add to the class:

public:
  void RunBackgroundTask();
}

After this, replace in the CPP file of the dialog all CDialog words with CBackgroundTaskDialog too and add the following members code:

void your_dialog_class_name::RunBackgroundTask()
{
  //Here you should add the code for the long-term process to do
  
  //At regular intervals you should call then 
  //CheckForBackgroundTaskAbort function
  //to check for an abort signal. If the function 
  //returns TRUE, usually simply return
}

To start the background process, you must use the StartBackgroundTask function. It returns a value of 1 if all is ok or less than 0 if an error occurs. The function is usually used in the OnInitDialog function.

BOOL your_dialog_class_name::OnInitDialog()
{
  // Code added by MFC AppWizard and your own code

  // Example code to add:

  if (StartBackgroundTask() < 0)
  {
     AfxMessageBox(_T("Error"));
     PostMessage(WM_CLOSE, 0, 0);
     return TRUE;
  }

  return TRUE;
}

At last, if you want to abort the background process, call the StopBackgroundTask function.

See the example project because it has more explanations.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mauro Leggieri
Web Developer
Argentina Argentina
Member
My name is Mauro Leggieri. I am 30 year-old, married and have a child.
 
I am a system engineer (UTN university) and am being programming for more than 20 years from the C64 to the PC and some microcontrollers.
 
Mostly of my time, I program games for Windows.
 
Soon, my site http://www.mauroleggieri.com.ar

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
AnswerRe: what to do when using multiple base class?memberMauro Leggieri27 Dec '05 - 8:50 
Hi Kane,
 
I'm writing a fast answer because I'm at work. Please, let me know if you need further assistance.
 
You should add to BackgroundTaskDialog.cpp and .h the three dialog constructors...
 
CBackgroundTaskDialog(UINT uResourceID, CWnd* pParent = NULL);
CBackgroundTaskDialog(LPCTSTR pszResourceID, CWnd* pParent = NULL);
CBackgroundTaskDialog();
 
... and their implementations. The first one is already defined and implemented so you must add the second and the third.
 
In the implementation remember to call the corresponding CDialog base member function and put
 
hKillBackgroundThreadEvent = hDoneBackgroundThreadEvent = NULL;
lpBackgroundThread = NULL;
 
inside each constructor in order to initialize the variables.
 
Then you can change the HMXDialog.h file to make CHMXDialog a derived class of CBackgroundTaskDialog and the HMXDialog.cpp to call CBackgroundTaskDialog constructors instead of CDialog ones.
 
Best regards,
Mauro H. Leggieri

GeneralRe: what to do when using multiple base class?member_kane_29 Dec '05 - 7:04 
thanks Smile | :) with your help i managed to do it Smile | :)
 
"Some guys hack just to get themselves a girlfriend.What a pathetic reason huh ?"
GeneralRe: what to do when using multiple base class?memberMauro Leggieri29 Dec '05 - 8:49 
Wink | ;) Perfect.
 
Happy new year!
 
Mauro.
GeneralRC -4 after 85 DoModal()ssussAnonymous29 Jun '05 - 3:40 
Hello,
 
alfter calling the StartBackgroundTask in the Initdialog functions
it returns -4!
 
Some known Problems?
 
regards
alex

GeneralRe: RC -4 after 85 DoModal()smemberMX-Mauro29 Jun '05 - 12:36 
Hi Alex,
 
As you see in the code, return value -4 implies that AfxBeginThread failed. I think ( really i'm guessing Smile | :) ) that the problem can be a memory, resource and/or gdi object leak in the code that is consuming system resources and then Windows cannot create the new thread.
 
Also, if you are using the StopBackgroundTask with a timeout, check if the function is really waiting the thread to finish or the function is terminating it.
 
Tell me if you have any news.
 
Best regards,
Mauro H. Leggieri

QuestionAny new version?sussAnonymous23 Mar '05 - 14:23 
Frown | :( the program crashed!
Any new version?
AnswerRe: Any new version?memberMX-Mauro29 Jun '05 - 13:00 
Hi,
 
Sorry for the very late answer. I haven't made modifications to the code. Tell me more about the program crash so I can help you.
 
Best regards,
 
Mauro H. Leggieri.
GeneralRe: Any new version?memberdennisV17 Aug '05 - 21:56 
I'm not the original poster of that question, but the crash that happens after starting/stopping a few times is still there it seems, so if you've fixed it, could you please post the code that needs to be changed?
 
Thanks.
 
// MCP, MCSD
// Software for animal shelters
// http://www.smartpethealth.com
GeneralRe: Any new version?memberMX-Mauro18 Aug '05 - 1:29 
Hi Dennis,
 
The version at codeproject is the latest and I make the test of starting and stopping the background task and seeing if there is any leak and nothing happens.
 
Please send me more details about the crash message and if it occurs in the demo app I uploaded. I want to resolve the problem if there is one.
 
Best regards,
Mauro H. Leggieri

GeneralRe: Any new version?sussAnonymous18 Aug '05 - 3:43 
Hi,
 
It's not a leak actually, it's a crash. I don't have the call stack at the moment (different computer), but if you do start-stop a few times quickly (15-20 times?), then it's going to come down crashing.
 
If you can't reproduce it, I'll try to get you a call stack and the offending variable sometime soon.
GeneralRe: Any new version?memberdennisV18 Aug '05 - 3:45 
That was me, not logged in Laugh | :laugh:
 
// MCP, MCSD
// Software for animal shelters
// http://www.smartpethealth.com
GeneralRe: Any new version?memberMX-Mauro18 Aug '05 - 7:40 
Hi Dennis,
 
I made a very quick start/stop sequence as you (also using the spacebar to hit the button faster than mouse clicks) and nothing happens. I have a Pentium 4 1.8Ghz with 256mb ram. Send me the stack trace when you can to check.
 
Greetings, Mauro.
GeneralBackgound processmemberEmmanouel22 Jun '04 - 1:29 
Hello,
 
I am trying to set up a windows .net application form that apart from everything else would run a background process for downloading a web page and set it up as a backgound wallpaper.
 
I am trying to use the code in the backgound task dialog, i've managed to define Runbackgroundtask with the code i would like to use but when i try to use the startbackgoundtask in the initialiseComponent in order to run the backgound process, i get a compile error of
 
C2352: 'CBackgroundTaskDialog::StartBackgroundTask' : illegal call of non-static member function
 
Any sugestions ?
 
Thanks

GeneralRe: Backgound processmemberMX-Mauro22 Jun '04 - 4:15 
Hi,
 
According to MSDN the problem arises when you call a nonstatic member from a static one or when you directly use the 'CBackgroundTaskDialog::StartBackgroundTask()' sentence to try to start the background task.
 
The CBackgroundTaskDialog is used as a base class of the dialog and you must call the StartBackgroundTask function using, for e.g., this->StartBackgroundTask();
 
If you can send me the piece of code that generates the problem I shall have a better view of the problem.
 
Best regards, Mauro H. Leggieri.
GeneralSingle-threaded applicationmembermaciejr9 May '04 - 21:19 
Hi,
 
I am trying to use your class for my program, but with a single-threaded program design it is not straightforward.
 
The effect I wanted is: during a lengthy operation (such as reading a large data file referenced in a document being loaded) a "Patience" dialog box with a simple message appears until the operation is complete. However, the lengthy operation is called in a sequence of other operations, so the main thread would have to "stop and wait" until the background thread finishes as if everything was in one thread. Still, if I simply displayed a dialog box and then go on processing, the program window would not be redrawn until the lengthy operation is completed.
 
To avoid a major redesign of existing code I made it work like this:
 
1. My code calls the DoModal() method of a dialog box displaying a "Please wait..." prompt (say: CPatience). DoModal() gives the "illusion" of a single-threaded operation.
 
2. In OnInitDialog() of CPatience I start a background thread to do lengthy processing (i.e. call StartBackgroundTask()).
 
3. After the lengthy operation is finished I call EndDialog(IDOK) of CPatience (from RunBackgroundTaskProc()).
 
It seems to work. Do you think it is ok or is there a major design-flaw in my logic?
 
Best regards,
 

 
Maciej.
GeneralRe: Single-threaded applicationmemberMX-Mauro10 May '04 - 2:05 
Hi Maciej,
 
In the RunBackgroundTaskProc you must call CheckForBackgroundTaskAbort function with some periodicity (eg. inside a loop)
 
The function check if a user want to stop the background process (eg. calling StopBackgroundTask in a cancel button) but it will also process the Windows messages that causes repainting and more.
 
Best regards, Mauro.
GeneralRe: Single-threaded applicationmemberdis14119 Dec '06 - 21:57 
aside from the drawing, what is your opinion on how the work dialog is hidden, ie EndDialog(IDOK) from RunBackgroundTaskProc()
GeneralProgram crashed.memberWREY16 Apr '04 - 11:59 
After starting and stopping it a few times, the program crashed.
 
Repeated it again, and again it crashed.
 
Frown | :(
 
William
 
Fortes in fide et opere!
GeneralRe: Program crashed.memberMX-Mauro16 Apr '04 - 12:03 
Hi William,
 
I am sending an update to fix a problem when the background task function send a message to a windows.
 
Best regards, Mauro.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 20 Apr 2004
Article Copyright 2004 by Mauro Leggieri
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid