I have a function that run over hours.. I want that on click on a button, this function will start to run, and on click on anoter button (Stop) this function will be stopped (break) - but the problem is that the form become "stuck" when the function is running - and there is no option to click on button Stop. So how to make the function run without stucking the form?
The second question is how i make the button Stop - how I break a function while it runs (outside the function...)
My reason is to create a new form that will only run the function..and the main form will can close this form while in runs - is there better solution?
thanks!
Read a bit about the concept of threads. WinAPI provides both functions to start new thread and control it, search MSDN for them - creating a new form is not the way to go.
In your main thread, create a worker thread for your computation task which runs for hours. The Win32 API CreateThread
should help on this. See the function help here, and an example here.
Then, you need to communicate with your worker thread, specifically, inform it to stop when your Stop button is clicked. Quite a few ways, PostThreadMessage
should be one of the most handy one to do this. Refer to the function help here.
So, when the Stop button is clicked, a message would be post to your working thread, and your working thread periodically checks whether such "Stop" signal is emitted by your main thread. You can decide how "periodically" it checks, which in turn decides how responsive your working thread is when "Stop" is signaled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With