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 "stu开发者_JAVA技巧ck" 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 can use .NET 4, look at the Task Parallel Library. That is by far the easiest way to handle threading for a .NET (including WinForms) application.
http://msdn.microsoft.com/en-us/library/dd460717.aspx
Using with C++:
http://msdn.microsoft.com/en-us/library/gg675934.aspx
Your background code can simply run in a task, and the start/stop buttons can set a flag indicating to the task whether or not it should process work.
It sounds like, right now, you are doing work on the same thread that is processing messages to the user interface. If the user interface thread is busy doing calculations, it can't pick up the click event for the stop button.
精彩评论