"Interactive" Sleep in C++
I started to learn c++ a while ago. I done a lot of console program with Visual Studio 2010 and now I want to make win32 programs. I read a lot of tutorial and I understand the basics now.
I made a button which call another function. The function is doing great everything working. But there are Sleep(x) in this function and the GUI isn't responding while the Sleep doesn't end. The function is done in 60 sec because there is a lot of Sleep in it but it is do everything what is should just do GU开发者_如何学编程I isn't responding this time.
I think I know the source of this problem. In my opinion the problem is Sleep totally pause the application (Windows say: not responding).
How can I make a Sleep/pause which doesn't freeze the GUI? Is there a function or I must do it in a totally different way?
Thank you in advance!
In my opinion the problem is Sleep totally pause the application
Yes.
How can I make a Sleep/pause which doesn't freeze the GUI?
Why do you need to sleep in the first place? If the function is misbehaving, you can always run it in a background thread (but be aware that this adds quite a bit of complexity and difficulty). Normally, you shouldn't need to sleep at all. If you do have to sleep, then make it a loop that spins until enough time passes, processing the events from the OS and calling Sleep(0)
which yields the timeslice.
Can you break your code into sections and use timers instead of Sleep? That will keep the message pump running. Look at this article in MSDN on using timers: http://msdn.microsoft.com/en-us/library/ms644901%28v=VS.85%29.aspx
Either offload the work to a separate thread (see CreateThread
) or, use PeekMessage
et. al in a tight loop to process window messages and keep the GUI alive.
Of course you should ask yourself whether you really need to sleep. As you said, a sleep in the main thread (the thread that polls the message pump) prevents any GUI processing.
You have to use threads. Remember that if you have a long-running process in your GUI, you have to create a thread and let it deal with all of your code—which in this case contains many sleep instructions. Once the thread finishes its job, it will notify you and you can then extract data from it.
精彩评论