I want to put my program to a sleep for a couple of seconds. When i use thread.sleep(x) entire program doesn't respond. According to this article -> http://msdn.microsoft.com/en-us/library/hh184840(v=VS.92).aspx application which is not responsible for 3 seconds doesn't pass the certification :/ (i have to wait 5 seconds). Does anybody know a solution for this problem?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
Looks like a job for ThreadPool.QueueUserWorkItem
You need to rethink what you are trying to do with your pause. It's a bit hard to say given that we don't have much info about what you try to achieve with this pause, but I'll give an example here to illustrate how you can get the wanted effect without having to pause the entire app (which you should never do).
Say you want to download file A, then wait 5 sec ,then download file B. You do this by running something like this:
Also, it's prefferable to make the actual download-calls async (if it is downloading you are doing), just to make sure that you don't feeze the GUI.
Alternativly, you can do both the downloads in the background-thread like this:
Don't sleep the main thread of your application. Instead, do whatever you need to do that requires waiting in a background thread of your application.
If you put a Thread.Sleep() call in the main thread of your application, the app will become unresponsive to the UI message loop behind the scenes, as you see. This is because you're blocking execution while handling one message (the UI event that triggered the wait), so no other messages for the app can be handled.
Instead, structure this code to run asynchronously. I'm guessing there's some method that contains most of the heavy lifting including the sleep. As long as that's not an event handler (refactor it if it is) you can set up a second thread to run this method, and add a "callback" method that the method will call when it finishes, which will update the UI with the results. It's a little more work, but it keeps the app responsive, and it's generally good practice especially on multicore devices (even phones are getting dual-core CPUs nowadays). There are many ways to set up multithreaded operations. Delegate.BeginInvoke is my favorite:
Disclaimer:
Thread.Sleep(n)
anywhere is pretty much a "code smell", meaning it's an indicator that other code in the app is going to be a problem as well. I generally avoid using it at all (I have never encountered a scenario whereThread.Sleep
must be used).In your case, however, a simple drop-in replacement for
Thread.Sleep(5000)
might be to just do this:You'll achieve an overall wait time of 5 seconds, but the UI will never be locked for more than half a second.