开发者

Programming problem with a continuous loop and buttons?

I have to design a program that uses a main loop to keep track of time and to perform continuous checks. Also I ha开发者_如何学编程ve a gui system that can alter things in the system. The question is:

If i run a continuous loop that doesnt stop until the system exits, will the user be able to interact with the GUI I have set up, or will the loop have to stop running for the effect of pressing a button to take place? In other words, do i have to pause the loop, run the button command, then restart the loop, everytime a user interacts with the GUI? and if so, is there a way around this? Thanks to any and all who answer


Since you didn't state your platform, I will term my reply generically.

There are two patterns you can use: polling or interrupt / event driven.

Polling

The polling involves checking a semaphore or flag frequently to see if something happened. This is common in embedded systems. A background loops until an interrupt sets a flag then processes the event.

Interrupt / Event Driven.

In this pattern, a function is executed when an event occurs. For example, a function may be executed when a User clicks on the button.

On Desktop platforms (Mac, Linux, Windows, etc.), your situation is resolved by using multiple threads (of execution). Usually the GUI operation is on one thread and the main processing on another. This allows the program not to freeze the GUI when a button is clicked.

On my application, the GUI sets an event when the user clicks a button. The processing thread waits (sleeps, pends) on the event. The User clicks the button, the event is set. The processing thread wakes up and continues.


It seems that you are trying to do DOS-like programming in Windows which works the other way around. You should read something about Event Driven Programming. There should not be any main loop in your application. All interactions should be done through events. When user press the button - an event is fired. Instead of the loop you are describing you should create a timer that will execute a method that will do the necessary checks.

Hope this helped a bit.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜