Pedro Ferreira said:

I’m trying to create a UI thread to do constant background work, but I’m having some design problems.

The thread needs to fetch records from a database. do some processing on each record and, when there are no more records, sleep for 1 minute before check the database again. The process will be controlled with thread messages (to start, pause, query…).

My problem is where should I put the processing work. I need it to be
responsive between cycles, where the process waits for 1 minute, so I
can stop it in that period. My only idea is using OnIdle to do the work.
  But then, how should I make it real idle when waiting for 1 minute?

Could anyone give some hints on what is the way to go?

Scott McPhillips [VC++ MVP]

You can’t use Sleep and still be responsive to messages.  Instead of using Sleep you could use SetTimer in the main thread and post a message to the thread, or SetTimer to a hidden window within the thread, or you could use a loop within the thread and use MsgWaitForMultipleObjects within the loop.

MsgWaitForMultipleObjects has a timeout parameter that gives you the sleep period, but it also returns early if a message or event comes along.

Almond and Joseph M. Newcomer [MVP]

I would be strongly disinclined to use MsgWaitForMultipleObjects.  You don’t gain anything by using it over using WM_TIMER, and it requires that you have to write your own message pump, always a dangerous proposition.

BUT, SOME MORE DISCUSSION ABOUT THE UI THREAD AND WORKER THREAD…

Almond

Do not use UI threads for this kind of thing.

David

I would create a worker thread (not a UI thread) unless you need a UI thread for some specific purpose not apparent in this description.  The worker thread would do it’s work and then do a WaitForSingleObject() with a timeout of 1 minute (60000 ms), which causes WaitForSingleObject() to return when either the main thread sets an event for starting, pausing, querying, etc. or the 1 minute has elapsed.  If you need separate events each for starting, pausing, querying, etc. use WaitForMultipleObjects() instead of WaitForSingleObject().

Joseph M. Newcomer [MVP]

UI threads are actually ideal for this sort of thing.  Don’t be confused by the phrase ‘UI’ meaning something with windows; think of it as “a thread with a built-in queuing mechanism”.  They’re really very good for things that require timed events as the OP described.

There are some advantages to UI threads; for example, a UI thread has a built-in queue.
Also, for some kinds of interfacing require a message pump to deal with event handling.  I don’t do databases so I don’t know if databases have this requirement, but there are On-Anything handlers involved in the database interface, then a UI thread is required.

Tags: , , ,