- Sleep function (synchapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- Thread. Sleep Метод
- Определение
- Перегрузки
- Sleep(Int32)
- Параметры
- Исключения
- Примеры
- Комментарии
- Thread. Sleep Method
- Definition
- Overloads
- Sleep(Int32)
- Parameters
- Exceptions
- Examples
- Remarks
- Applies to
- Sleep(TimeSpan)
- Parameters
- Exceptions
- Examples
- Remarks
- Thread.Sleep() in C#
- 4 Answers 4
- Not the answer you’re looking for? Browse other questions tagged c# winforms or ask your own question.
- Linked
- Related
- Hot Network Questions
- Subscribe to RSS
- thread and Sleep
- 3 Answers 3
Sleep function (synchapi.h)
Suspends the execution of the current thread until the time-out interval elapses.
To enter an alertable wait state, use the SleepEx function.
Syntax
Parameters
The time interval for which execution is to be suspended, in milliseconds.
A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution.WindowsВ XP:В В A value of zero causes the thread to relinquish the remainder of its time slice to any other thread of equal priority that is ready to run. If there are no other threads of equal priority ready to run, the function returns immediately, and the thread continues execution. This behavior changed starting with Windows ServerВ 2003.
A value of INFINITE indicates that the suspension should not time out.
Return value
Remarks
This function causes a thread to relinquish the remainder of its time slice and become unrunnable for an interval based on the value of dwMilliseconds. The system clock «ticks» at a constant rate. If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on. To increase the accuracy of the sleep interval, call the timeGetDevCaps function to determine the supported minimum timer resolution and the timeBeginPeriod function to set the timer resolution to its minimum. Use caution when calling timeBeginPeriod, as frequent calls can significantly affect the system clock, system power usage, and the scheduler. If you call timeBeginPeriod, call it one time early in the application and be sure to call the timeEndPeriod function at the very end of the application.
After the sleep interval has passed, the thread is ready to run. If you specify 0 milliseconds, the thread will relinquish the remainder of its time slice but remain ready. Note that a ready thread is not guaranteed to run immediately. Consequently, the thread may not run until some time after the sleep interval elapses. For more information, see Scheduling Priorities.
Be careful when using Sleep in the following scenarios:
- Code that directly or indirectly creates windows (for example, DDE and COM CoInitialize). If a thread creates any windows, it must process messages. Message broadcasts are sent to all windows in the system. If you have a thread that uses Sleep with infinite delay, the system will deadlock.
- Threads that are under concurrency control. For example, an I/O completion port or thread pool limits the number of associated threads that can run. If the maximum number of threads is already running, no additional associated thread can run until a running thread finishes. If a thread uses Sleep with an interval of zero to wait for one of the additional associated threads to accomplish some work, the process might deadlock.
For these scenarios, use MsgWaitForMultipleObjects or MsgWaitForMultipleObjectsEx, rather than Sleep.
Windows Phone 8.1: This function is supported for Windows Phone Store apps on Windows Phone 8.1 and later.
WindowsВ 8.1 and Windows ServerВ 2012В R2: This function is supported for Windows Store apps on WindowsВ 8.1, Windows ServerВ 2012В R2, and later.
Thread. Sleep Метод
Определение
Приостанавливает текущий поток на заданное время. Suspends the current thread for the specified amount of time.
Перегрузки
Приостанавливает текущий поток на заданное количество миллисекунд. Suspends the current thread for the specified number of milliseconds.
Приостанавливает текущий поток на заданное время. Suspends the current thread for the specified amount of time.
Sleep(Int32)
Приостанавливает текущий поток на заданное количество миллисекунд. Suspends the current thread for the specified number of milliseconds.
Параметры
Количество миллисекунд, на которое приостанавливается поток. The number of milliseconds for which the thread is suspended. Если значение аргумента millisecondsTimeout равно нулю, поток освобождает оставшуюся часть своего интервала времени для любого потока с таким же приоритетом, готовым к выполнению. If the value of the millisecondsTimeout argument is zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. Если других готовых к выполнению потоков с таким же приоритетом нет, выполнение текущего потока не приостанавливается. If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended.
Исключения
Значение времени ожидания является отрицательной величиной и не равно Infinite. The time-out value is negative and is not equal to Infinite.
Примеры
В следующем примере метод используется Sleep для блокировки основного потока приложения. The following example uses the Sleep method to block the application’s main thread.
Комментарии
Выполнение потока не будет запланировано операционной системой на указанный период времени. The thread will not be scheduled for execution by the operating system for the amount of time specified. Этот метод изменяет состояние потока для включения WaitSleepJoin . This method changes the state of the thread to include WaitSleepJoin.
Можно указать Timeout.Infinite для параметра, millisecondsTimeout чтобы приостановить поток в течение неограниченного времени. You can specify Timeout.Infinite for the millisecondsTimeout parameter to suspend the thread indefinitely. Однако System.Threading Mutex Monitor EventWaitHandle Semaphore для синхронизации потоков или управления ресурсами рекомендуется использовать другие классы, такие как,, или. However, we recommend that you use other System.Threading classes such as Mutex, Monitor, EventWaitHandle, or Semaphore instead to synchronize threads or manage resources.
Системные тактовые импульсы с заданной скоростью, называемой разрешением часов. The system clock ticks at a specific rate called the clock resolution. Фактическое время ожидания может быть не равно указанному времени ожидания, так как указанное время ожидания будет изменено в соответствии с тактами времени. The actual timeout might not be exactly the specified timeout, because the specified timeout will be adjusted to coincide with clock ticks. Дополнительные сведения о разрешении часов и времени ожидания см. в разделе Функция Sleep из системных API Windows. For more information on clock resolution and the waiting time, see the Sleep function from the Windows system APIs.
Этот метод не выполняет стандартные конвейеры COM и SendMessage. This method does not perform standard COM and SendMessage pumping.
Если необходимо включить спящий режим в потоке, который имеет STAThreadAttribute , но вы хотите выполнить стандартные выгрузки com и SendMessage, рассмотрите возможность использования одной из перегруженных версий Join метода, указывающих интервал времени ожидания. If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread. Sleep Method
Definition
Suspends the current thread for the specified amount of time.
Overloads
Suspends the current thread for the specified number of milliseconds.
Suspends the current thread for the specified amount of time.
Sleep(Int32)
Suspends the current thread for the specified number of milliseconds.
Parameters
The number of milliseconds for which the thread is suspended. If the value of the millisecondsTimeout argument is zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended.
Exceptions
The time-out value is negative and is not equal to Infinite.
Examples
The following example uses the Sleep method to block the application’s main thread.
Remarks
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
You can specify Timeout.Infinite for the millisecondsTimeout parameter to suspend the thread indefinitely. However, we recommend that you use other System.Threading classes such as Mutex, Monitor, EventWaitHandle, or Semaphore instead to synchronize threads or manage resources.
The system clock ticks at a specific rate called the clock resolution. The actual timeout might not be exactly the specified timeout, because the specified timeout will be adjusted to coincide with clock ticks. For more information on clock resolution and the waiting time, see the Sleep function from the Windows system APIs.
This method does not perform standard COM and SendMessage pumping.
If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Applies to
Sleep(TimeSpan)
Suspends the current thread for the specified amount of time.
Parameters
The amount of time for which the thread is suspended. If the value of the timeout argument is Zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run. If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended.
Exceptions
The value of timeout is negative and is not equal to Infinite in milliseconds, or is greater than MaxValue milliseconds.
Examples
The following example uses the Sleep(TimeSpan) method overload to block the application’s main thread five times, for two seconds each time.
Remarks
The thread will not be scheduled for execution by the operating system for the amount of time specified. This method changes the state of the thread to include WaitSleepJoin.
You can specify Timeout.InfiniteTimeSpan for the timeout parameter to suspend the thread indefinitely. However, we recommend that you use other System.Threading classes such as Mutex, Monitor, EventWaitHandle, or Semaphore instead to synchronize threads or manage resources.
This overload of Sleep uses the total number of whole milliseconds in timeout . Fractional milliseconds are discarded.
This method does not perform standard COM and SendMessage pumping.
If you need to sleep on a thread that has STAThreadAttribute, but you want to perform standard COM and SendMessage pumping, consider using one of the overloads of the Join method that specifies a timeout interval.
Thread.Sleep() in C#
I want to make an image viewer in C# Visual Studio 2010 which displays images one by one after seconds:
When the program starts, it stops and just shows me the first and last image.
4 Answers 4
Thread.Sleep blocks your UI thread use System.Windows.Forms.Timer instead.
First declare your Timer and set it to tick every second, calling TimerEventProcessor when it ticks.
Your class will need the image1 array and an int variable imageCounter to keep track of the current image accessible to the TimerEventProcessor function.
Then write what you want to happen on each tick
Something like this should work.
Yes, because Thread.Sleep blocks the UI thread during the 2s.
Use a timer instead.
If you want to avoid using Timer and defining an event handler you can do this:
Not the answer you’re looking for? Browse other questions tagged c# winforms or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
thread and Sleep
I’m trying to understand how multi-threading works.
I have this code:
And the problem is when I run it, it stops waiting for std::this_thread::sleep_for(std::chrono::seconds(5)); and doesn’t show the next Hi I’m the function 1 from std::thread t1(function1); in the next loop, until the sleep thread ends.
1) Do you know why?
2) I want that the main continues the loop and don’t wait to the t2 to finish (sleep_for() from function2 is set to 5 seconds)
3 Answers 3
This is what your code does:
- Start thread 1
- Outputs a message
- Waits 1 second
- Outputs another message
- Start thread 2
- Outputs a message
- Waits 5 seconds
- Outputs another message
- Waits for both threads to finish
- (this will take roughly 5 seconds)
- Repeats indefinitely
You have stated that this isn’t what you meant to do.
I think, instead, you intended to have the «repeat» inside of each thread, so that they continue ticking independently and indefinitely, like this:
Now your code does this:
- Start thread 1
- Outputs a message
- Waits 1 second
- Outputs another message
- Repeats indefinitely
- Start thread 2
- Outputs a message
- Waits 5 seconds
- Outputs another message
- Repeats indefinitely
- Waits for both threads to finish
- (although neither ever will!)
With each thread now spinning independently, neither will ever «block» the other.