No Image

System threading thread sleep

СОДЕРЖАНИЕ
566 просмотров
10 марта 2020

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 topic. This method calls 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.

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 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 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.

Читайте также:  Добавление пользователя в sudoers

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.

Определение

Приостанавливает текущий поток на заданное время. 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. Дополнительные сведения о разрешении часов и времени ожидания см. в разделе функция спящего режима . For more information on clock resolution and the waiting time, see the Sleep function topic. Этот метод вызывает функцию Sleep из системных API Windows. This method calls 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.

Sleep(TimeSpan)

Приостанавливает текущий поток на заданное время. Suspends the current thread for the specified amount of time.

Параметры

Время, на которое приостанавливается поток. The amount of time for which the thread is suspended. Если значение аргумента millisecondsTimeout равно Zero, поток освобождает оставшуюся часть своего интервала времени для любого потока с таким же приоритетом, готовым к выполнению. 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.

Исключения

Значение timeout является отрицательным и не равно Infinite (в миллисекундах) или больше MaxValue миллисекунд. The value of timeout is negative and is not equal to Infinite in milliseconds, or is greater than MaxValue milliseconds.

Примеры

В следующем примере используется перегрузка метода Sleep(TimeSpan) для блокирования основного потока приложения пять раз, в течение двух секунд каждый раз. The following example uses the Sleep(TimeSpan) method overload to block the application’s main thread five times, for two seconds each time.

Комментарии

Выполнение потока не будет запланировано операционной системой на указанный период времени. 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.InfiniteTimeSpan для параметра timeout , чтобы приостановить поток в течение неограниченного времени. You can specify Timeout.InfiniteTimeSpan for the timeout 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.

Читайте также:  Adblock plus for mozilla

Эта перегрузка Sleep использует общее число целых миллисекунд в timeout . This overload of Sleep uses the total number of whole milliseconds in timeout . Доли миллисекунд отбрасываются. Fractional milliseconds are discarded.

Этот метод не выполняет стандартные конвейеры 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.

Функция Sleep делает задержку ровно на указанное время?

Или микросекунду с лишнем от реального времени?

Каким образом работает задержка времени, это реальное время или такт работы процессора?

У меня происходит большие задержки, но из-за Console.WriteLine , поэтому время задержки не определяется точно.

192 466 479 487 501 514 517 519 522 524 525 529 531 533 535 537 539 541 543 546 549 551 553 555 557 559

299 303 305 307 309 311 313 315 317 319 330 332 334

2 ответа 2

Почему происходит разница во времени? Немного теории о работе Sleep .

Поток может сообщить системе, что в течение некоторого времени его не нужно планировать на исполнение. Эта задача решается статическим методом Sleep . После чего система забирает поток у планировщика примерно на указанное время. То есть если вы говорите системе, что метод хочет приостановить работу на 100 мс , он будет приостановлен примерно на это время, но возможно пробудет в состоянии покоя на несколько секунд меньше или больше. Не забывайте, что Windows не является операционной системой реального времени. Поэтому поток, скорее всего, пробудится в указанное время, но по большому счету время его пробуждения зависит от остальных происходящих в системе процессов.

Если методу Sleep передать значение -1 или System.Threading.Timeout.Infinite то в результате поток окажется заблокированным на неограниченное время. При этом он будет существовать, и вы в любой момент сможете восстановить его стек и ядро.

Если методу Sleep передать значение 0 то это сообщит системе, что вызывающий поток освобождает ее от его исполнения и заставляет запланировать другой поток. Впрочем, система при отсутствии доступных для планирования потоков такого же или более высокого приоритета может снова запланировать исполнение потока.

Если методу Sleep передать значение 1 это включает принудительное переключение контекста, и Windows погружает поток в спящее состояние более чем на 1 мс , что обусловлено разрешением внутреннего системного таймера.

Комментировать
566 просмотров
Комментариев нет, будьте первым кто его оставит

Это интересно
Adblock
detector