Home » Developing U++ » U++ Developers corner » BackgroundTask
BackgroundTask [message #31240] |
Wed, 16 February 2011 13:52  |
|
As discussed in the thread about MT in theide, there is sometimes need to run some lengthy task in background, while the rest of Application stays responsive.
Ideal solution should use Thread in MT mode and ProcessEvents() in single threaded environment to achieve maximum effectiveness. Here is my first attempt to create such class:bool ProcessForeground(){
#ifdef _MULTITHREADED
DUMP(Thread::IsShutdownThreads());
return !Thread::IsShutdownThreads();
#else
Ctrl::ProcessEvents();
return true; //is it possible to detect application is being closed?
#endif
}
class BackgroundTask{
typedef BackgroundTask CLASSNAME;
#ifdef _MULTITHREADED
Thread t;
#endif
bool running;
void Watch(Callback task) {running=true; task(); running=false;}
public:
void Start(Callback task);
bool IsRunning() {return running;}
BackgroundTask():running(false){}
BackgroundTask(Callback task) {Start(task);}
};
void BackgroundTask::Watch(Callback task){
running=true;
task();
running=false;
}
void BackgroundTask::Start(Callback task){
#ifdef _MULTITHREADED
t.Run(THISBACK1(Watch,task));
#else
PostCallback(THISBACK1(Watch,task));
#endif
}
There is few requirements on the task and application that runs it. Task must call ProcessForeground() periodically, often enough to keep the UI responsive. If ProcessForeground() returns false, the task must finish as soon as possible. In MT mode the application must call Thread::ShutdownThreads(), so that any running tasks know that it is time to terminate itself.
In attachment there is a full code of a testing app. Known bugs: In ST mode you must close the window twice (press Alt+F4 or cross button twice), to make it really close. Probably easy to fix. In MT, calling ShutdownThreads assumes that there are no threads expected to run even after the Background tasks are terminated. This should be rarely problem, but to have a peace in mind, I would prefer separate solution.
I'm looking forward to your comments,
Honza
-
Attachment: bgtask.cpp
(Size: 1.43KB, Downloaded 409 times)
[Updated on: Wed, 16 February 2011 13:59] Report message to a moderator
|
|
|
Goto Forum:
Current Time: Sun Apr 27 10:54:15 CEST 2025
Total time taken to generate the page: 0.02886 seconds
|