Environment: .net 3.5 WinForms application
I am looking for some ideas how to stop / interrupting a Windows Form application, e.g. when “something” takes too long.
A typical scenario is reading large amount of data from a backend system and the user shall be able to press some key immediately stopping the loading.
- Normal events are not responsive enough, since the backend call somehow consumes so much time, they are not reacting in promptly fashion.
- In my read methods I have added explicit checks – but I cannot add such checks in 3rd party frameworks. Also it is somehow not a very nice approach.
Maybe someone has an idea how to reliable and promptly stop some running methods. Is there an interrupt I can use?
Regards HW
That’s not how it works. Understand the “message loop” is pretty important, be sure to read up on it. In a nutshell, Windows can only tell your program that a button was clicked when the main thread of program is idle. Your main thread should always be idle, ready to jump into action when some bit of work needs to be done. Like painting your form or processing a keystroke. Or doing something when the user clicks the Cancel button.
Which means that something else needs to do the heavy lifting. A thread. By far the best way to get started in the troublesome world of threading is the BackgroundWorker class. It has a CancelAsync() method, explicitly designed to do what you want to do. Be sure to review the code sample provided in the MSDN Library article for this method.