Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a function "In Background" of a WinForm (VS2010 c++)

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!

like image 999
DudiD Avatar asked Jul 31 '11 14:07

DudiD


2 Answers

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.

like image 161
Griwes Avatar answered Oct 13 '22 20:10

Griwes


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.

like image 2
BrandonSun Avatar answered Oct 13 '22 20:10

BrandonSun