- Как сделать задержку в программе без зависания формы
- Как в C# сделать задержку
- Решение
- Sleep function (synchapi.h)
- Syntax
- Parameters
- Return value
- Remarks
- Thread. Sleep Method
- Definition
- Overloads
- Sleep(Int32)
- Parameters
- Exceptions
- Examples
- Remarks
- Applies to
- Sleep(TimeSpan)
- Parameters
- Exceptions
- Examples
- Remarks
- C# Windows Forms Thread.Sleep() Doesn’t work?
- 1 Answer 1
Как сделать задержку в программе без зависания формы
Доброго времени суток
Никак не получается решить одну задачу. Допустим, есть форма с одной кнопкой. Нужно, чтобы через 3 секунды после нажатии на эту кнопку надпись на ней менялась. Я знаю, что это очень легко делается с помощью таймера, но в моем случае все не так просто. Мне нужно, чтобы при нажатии на кнопку в обработчике этой кнопки вызывался этот таймер, и по завершении его (таймера) работы (через 3 секунды) обработчик продолжил выполняться. Я пробовал сделать задержку Thread.Sleep(3000) и после нее изменить надпись, но в таком случае форма зависает на 3 секунды, что, в принципе, логично. Вопрос в том, как сделать, чтобы она не зависала?
Заранее благодарен за помощь
Как сделать задержку в программе?
Dalay в программе. Как установить заданный timeout?
Как правильно сделать задержку, ожидать событие в программе?
Вот, к примеру, алгоритм: Запуск программы Подготовка данных Запуск стороннего приложения.
Как сделать задержку без загрузки процессора?
В общем хочу сделать менюшку в Ацессе, таким образом, чтобы при наведении на кнопочку, но не.
Как сделать задержку перед отправкой формы
Есть форма регистрации 18
То, что вы хотите — невозможно. Нельзя создать команду, которая будет чего-то ждать 3 секунды, не блокируя при этом поток. Но можно сделать видимость активности формы, примерно так:
ахах, manualEventReset.
Зачем? ты используешь фоновый поток, и при вызове ManualEventReset.Wait все равно блокируешь текущий поток, то есть ты сводишь на нет использование этого фонового потока. убери его.
Добавлено через 5 минут
В фоновом потоке:
Добавлено через 2 минуты
при этом основной поток не будет виснуть
Еще один способ, не совсем адекватный конечно, но имеет право на жизнь:
Всем спасибо, вроде понятнее стало
Как в C# сделать задержку
Как сделать задержку в программе без зависания формы
Доброго времени суток 🙂 Никак не получается решить одну задачу. Допустим, есть форма с одной.
как сделать управляемую задержку
Thread.Sleep(10000); — не управляемая — управляемая int ct=0; while (ct 20
Что означает Task ибо такой код unity не видит. Это типо объект или что?
Добавлено через 1 минуту
Решение
Бляха да что ж вы меня не понимаете мне нужно чтоб не персонаж задерживался а код.
например изменился размер подождать некоторое время и если игрок не отпустил клавишу вернуть значение размера
Добавлено через 1 минуту
нет у меня только 2.0 и 2.0 subset
Добавлено через 1 минуту
Тематические курсы и обучение профессиям онлайн Профессия С#-разработчик (Skillbox) Архитектор ПО (Skillbox) Профессия Тестировщик (Skillbox) |
Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь или здесь.
Task.Delay или как правильно сделать задержку
Привет! Выручайте. Такая проблема: в цикле отрисовываю объекты Graphics меняя цвет одного из них.
Как сделать задержку?
package sevak_avet; import java.util.Calendar; import java.util.GregorianCalendar; import.
Как сделать задержку ?
к примеру вот программа. Что надо дописать и куда для задержки изображения ? /* Дане.
Как сделать задержку C++
#include #include #include using namespace std; double.
Как сделать задержку ?
При наведении на элемент , появляется окно, но как только я отвожу курсор , окно пропадает , как.
Как сделать задержку 1 ms ?
Частота cpu= 41 780 000 Hz. В сети нашел следующий код: long volatile a=def_msec*ms;.
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 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.
C# Windows Forms Thread.Sleep() Doesn’t work?
But there’s simply no delay. it just jumps through. I tried using both Task.Delay and Thread.Sleep but non of them actually delay. Also I’m a new programmer so take it easy on me.
1 Answer 1
Thread.Sleep does delay the execution as expected, but you run this code on the same Thread that is printing the UI therefore no Update is visible.
An easy fix for this is Task.Delay (you need to mark the function as async ):
To mark the function async add the async keyword to the function call
You should read some basics about windows GUI Thread and async programming.
A very basic explanation of the UI Thread: When you call Form.Show or Form.ShowDialog the application is starting a so called message loop. This message loop does process mouse and keyboard events of the window shown. This message loop does aswell handle the drawing of the window. Therefore if this thread is locked up, you application becomes unresponsive. A Button Click handler (and all other handlers of you Window) are processed by this same Thread. If you block the execution in one of this handlers (as you did with Thread.Delay ) the window is unresponsive (not processing events and not redrawing) in this Time.
To overcome this issue one solution is to work with async and await . This two methods do a lot of compiler magic to make this work as one would expect (check the link for more information, you definitely should!)