Using Delphi 7 & UIB, I'm running database operations in a background thread to eliminate problems like:
- Timeout
- Priority
- Immediate Force-reconnect after network-loss
- Non-blocked UI
- Keeping an opened DB connection alive
- User canceling
I've read ALL related topics here, and realized: using while isMyThreadStillRuning and not UserCanceled do sleep(100); end; isn't the recommended way to do this, but rather using TEvent.WaitFor(3000)....
The solutions here are either about sending signals FROM or TO... the thread, or doing it with messages, but never both ways.
Reading the help file, I've also found TSimpleEvent, which seems to be easier to use.
So what is the recommended way to communicate between Main-UI + DB-Thread in both ways?
Should I simply create 2+2 TSimpleEvent?
- to start a new transaction (thread should stop sleeping)
- force-STOP execution
- to signal back if it's moved to a new stage (transaction started / executed / commited=done)
- to signal back if there is any error happened
or should there be only 1 TEvent?
Update 2:
First tests show:
- 2x
TSimpleEventis enough (1 for Thread + 1 for Gui) - Both created as public properties of the background thread
- Force-terminating the thread does not work. (Too many errors impossible to handle..)
- Better to set a variable like (Stop_yourself) and let it cancel and free itself, (while creating a new instance from the same class and try again.)
- (still work in progress...)
You should move the query to a
TThread. Unfortunately, anonymous threads are not available in D7 so you need to write your ownTThreadderived class. Inside, you need its own DB connection to prevent shared resources. From the caller method, you can wait for the thread to end. The results should be stored somewhere in the caller class. Ensure that the access to parameters of the query and for storing the result of the query is handled thread-safe by using a TMutex or TMonitor.