Capture a Cancel Event

J

joelcochran

I have an application that executes SQL queries against a database.
When the user presses "Execute", I change the cursor to "Wait" while
the query executes and back to "Default" when it is complete.
Occasionally, a user will realize the query was mistaken and wants to
Cancel the query mid-request.

Is there a way I can do that? Can I have a button or something that is
available while in "Wait" mode? Can I add a listener to my RunSQL
Event that will effectively Cancel itself?

Thanks,

Joel
 
G

Guest

Prior to 2.0 you will need to execute your query on a secondary thread
instead of the primary UI thread. Your form will switch its UI to "cancel"
mode and start the query. Until the secondary thread completes the form will
simply wait. If the user presses the Cancel button then you can notify your
secondary thread (normally through a ManualResetEvent) to terminate.
Depending on where the secondary thread is in its execution will determine
how long it will actually take to cancel. If you are, for example, still
waiting for a long query from the DB then the secondary thread is effectively
blocked until the query comes back. Nothing nice you can do there short of
aborting the thread which will lead to unpleasant issues. However your main
thread can dismiss the form and continue on so the user perceives the action
as being cancelled when in fact it is still running. Eventually however your
secondary thread will unblock, realize it should cancel and then simply go
away without processing any results (or stop processing any results already
received). If the user does not cancel the operation then eventually when
the secondary thread completes it'll have to notify the "cancel" form to go
away. This complicates the UI because the secondary thread can't write to
any UI controls so if this functionality is needed then the secondary thread
will have to revert to eventing or Invoke.

For relatively short-lived queries you should use the thread pool. For
longer queries you should create your own thread. Of course the overhead for
cancelling an operation (and the complexity added to the UI) is only worth it
when a query can take a long time to run.

In 2.0 the BackgroundWorkerThread (or whatever they are calling it now) is
designed for cases like this and should be used instead. Also in 2.0 is
asynchronous queries so you can also work around the issue of a blocking
query call.

Michael Taylor - 7/3/05
 
J

joelcochran

Thank you for the detailed reply. I'm a thread novice, so I'll have to
go read up on that, but it sounds like what I need. Thanks for the
input.

Joel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top