Link to home
Start Free TrialLog in
Avatar of ChenChen
ChenChenFlag for Afghanistan

asked on

question about adAsyncExecute option

When you run a query in the Query Analyzer from a client PC, all work will be done on the server,  If you open the task manager you will see that the usage of client's CPU hardly get increased at all. but at the same time the GUI in client PC still keeps responding, there is even a moving timer.
However, I tried to execute the same query in my VB program (running on the same PC) using command object. the problem I have is if I use adAsyncExecute option, and keep a while loop to check command.state = adStateExecuting, the VB GUI will be responding but CPU usage will be up to about 50%; and If I don't use the option, CPU usage won't increase but it freezes up the GUI.

Does anyone know how to keep CPU usages low and program responding at the same time, like the Query Analyzer does?

Thanks in advance
Chen
ASKER CERTIFIED SOLUTION
Avatar of Jai S
Jai S
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ChenChen

ASKER

thankyou for your comment, but I am not familar with multi-threading, please explain. Thanks
Avatar of KirillMueller
KirillMueller

If you are using VB6, you cannot use multithreading. Use a While loop that calls DoEvents/Sleep, and you'll reduce CPU usage while maintaining responsiveness of your app:

Public Declare Sub Sleep Lib "kernel32" Alias "Sleep" (ByVal dwMilliseconds As Long)

Sub ExecuteSomeQuery()
   ...
   myCommand.Execute ..., adAsyncExecute
   Do While myCommand.State = adStateExecuting
      DoEvents ' this will ensure that your app is responsive
      Sleep 1 ' this will put your process asleep for 1 millisecond or so
   Loop
   ...
End Sub

My example does not cover issues like error handling. Remember that you should, as a rule of thumb, disable all of your GUI except of your "cancel" button while you are in such a loop.

Note that this approach works for VB.NET, too, however, using threads is somewhat more elegant. Also, you might want to substitute the call to Sleep with something like

Thread.Sleep(1)

.
The GUI might still be responsive if you leave out DoEvents, however, it does no harm in this particular situation.
KM...i think it will be appropriate to check the links provided before comment "If you are using VB6, you cannot use multithreading." thnx
Well, messing with CreateThread in VB6 is somewhat unsupported, good luck to you :-) I've tried that ages ago, it didn't work out for me for reasons I don't know anymore.

Waiting in a sleeping loop is not as elegant as using a worker thread, but it's guaranteed to work on VB6, and it might be simpler, too.