I have an application that is running some long search methods. Let’s imagine the user needs to cancel the search he/she started. How would I go about stopping a running method through the use of a cancel button?
How are you performing the search? Loop/Database/Other?
Are they in a thread? They probably should be if they’re running code that runs long enough where a user might need to cancel it.
Your code should check UserCancelled at frequent intervals. And this only works in a thread.
Thanks for the input gentlemen. I am running the searches using a loop and depending on the size of the volume being searched, this could take a couple of hours or more. The search methods are not in a thread because I haven’t figured out how to get a thread to work because I am trying to update a Listbox frequently to track the search hit results/progress.
I highly recommend taking a look in Examples/Desktop/UpdatingUIFromThread/ ad the UIThreadingWithTask project. We use a variation of this for ALL of our threads. Once you understand how it works it becomes easy and you can still update your listbox the track the results.
Sorry Bob, but I have looked at that example numerous times and no matter how I try, I am just unsuccessful at getting threads to work in my app.
I’m sorry, but that’s they way to do it. I have my own variation but I don’t think it would make any sense to you either since it uses the same technique of using a timer to put the event on the Main thread.
Seriously, threads are so useful I would pick that example apart until you understand it. If you don’t get why it works, start a new thread and we’ll try and walk you through it.
add a Property
UserHasCanceled as Boolean to the window, set it to false as default
In the thread your loop should look like this
For i as integer = 1 to 1000000
If UserHasCanceled then
UserHasCanceled = False
Exit for i
// your code
Have a Cancel button with the code
UserHasCanceled = True
Bob and Markus,
Thanks for the input. I will continue to see if I can get threading to work.
I do a lot of what you describe. Definitely learn to use the Task class. UI updates, elegant cancels, and a responsive app all depend on this.
There are also a number of MBS methods that can manipulate GUI elements from a thread in a thread-safe manner that I use when I’m lazy.