System windows forms timer system timers timer

Timer Class

Definition

Implements a timer that raises an event at user-defined intervals. This timer is optimized for use in Windows Forms applications and must be used in a window.

Examples

The following example implements a simple interval timer, which sets off an alarm every five seconds. When the alarm occurs, a MessageBox displays a count of the number of times the alarm has started and prompts the user as to whether the timer should continue to run.

Remarks

A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.

When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.

This class provides methods to set the interval, and to start and stop the timer.

The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.

Constructors

Initializes a new instance of the Timer class.

Initializes a new instance of the Timer class together with the specified container.

Properties

Gets a value indicating whether the component can raise an event.

(Inherited from Component) Container

Gets the IContainer that contains the Component.

(Inherited from Component) DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component) Enabled

Gets or sets whether the timer is running.

Gets the list of event handlers that are attached to this Component.

(Inherited from Component) Interval

Gets or sets the time, in milliseconds, before the Tick event is raised relative to the last occurrence of the Tick event.

Gets or sets the ISite of the Component.

(Inherited from Component) Tag

Gets or sets an arbitrary string representing some type of user state.

Methods

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject) Dispose()

Releases all resources used by the Component.

(Inherited from Component) Dispose(Boolean)

Disposes of the resources, other than memory, used by the timer.

Determines whether the specified object is equal to the current object.

(Inherited from Object) GetHashCode()

Serves as the default hash function.

(Inherited from Object) GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject) GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component) GetType()

Gets the Type of the current instance.

(Inherited from Object) InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject) OnTick(EventArgs)

Raises the Tick event.

Starts the timer.

Stops the timer.

Returns a string that represents the Timer.

Events

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component) Tick

Occurs when the specified timer interval has elapsed and the timer is enabled.

Компонент Timer (Windows Forms) Timer Component (Windows Forms)

Компонент Windows Forms Timer вызывает событие через определенные интервалы времени. The Windows Forms Timer is a component that raises an event at regular intervals. Этот компонент предназначен для работы в среде Windows Forms. This component is designed for a Windows Forms environment.

в этом разделе In This Section

Общие сведения о компоненте Timer Timer Component Overview
Основные понятия, связанные с компонентом Timer, который служит для настройки отклика на периодические события в приложении. Introduces the general concepts of the Timer component, which allows you to set up your application to respond to periodic events.

Ограничения свойства Interval компонента Timer в Windows Forms Limitations of the Windows Forms Timer Component’s Interval Property
Описываются известные ограничения на интервал таймера, которые могут влиять на его применение. Describes known limitations of the timer’s interval that may affect how you can use it.

Справочник Reference

Класс System.Windows.Forms.Timer System.Windows.Forms.Timer class
Справочная информация о классе, используемом для таймеров форм Windows Forms, и его членах. Provides reference information on the class, used for Windows Forms timers, and its members.

Класс System.Timers.Timer System.Timers.Timer class
Справочная информация о классе System.Timers.Timer, используемом для серверных таймеров. Provides reference information on the System.Timers.Timer class that is used by server-based timers.

Элементы управления для использования в формах Windows Forms Controls to Use on Windows Forms
Полный список элементов управления Windows Forms со ссылками на информацию об их применении. Provides a complete list of Windows Forms controls, with links to information on their use.

таймеры Timers

.NET предоставляет два таймера, которые можно использовать в многопоточной среде: .NET provides two timers to use in a multithreaded environment:

  • System.Threading.Timer, который выполняет метод одного обратного вызова в потоке ThreadPool с регулярными интервалами. System.Threading.Timer, which executes a single callback method on a ThreadPool thread at regular intervals.
  • System.Timers.Timer, который по умолчанию порождает событие в потоке ThreadPool с регулярными интервалами. System.Timers.Timer, which by default raises an event on a ThreadPool thread at regular intervals.

В некоторых реализациях .NET может содержать дополнительные таймеры: Some .NET implementations may include additional timers:

  • System.Windows.Forms.Timer — компонент Windows Forms, который вызывает событие через определенные интервалы времени. System.Windows.Forms.Timer: a Windows Forms component that fires an event at regular intervals. У этого компонента нет интерфейса пользователя. Он предназначен для однопоточной среды. The component has no user interface and is designed for use in a single-threaded environment.
  • System.Web.UI.Timer — компонент ASP.NET, который выполняет асинхронную или синхронную обратную передачу веб-страницы с регулярными интервалами. System.Web.UI.Timer: an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
  • System.Windows.Threading.DispatcherTimer — таймер, интегрированный в очередь Dispatcher, которая обрабатывается с заданными интервалом и приоритетом. System.Windows.Threading.DispatcherTimer: a timer that is integrated into the Dispatcher queue which is processed at a specified interval of time and at a specified priority.
Читайте также:  Disable windows 10 gpo

Класс System.Threading.Timer The System.Threading.Timer class

Класс System.Threading.Timer позволяет непрерывно вызывать делегат через определенные интервалы времени. The System.Threading.Timer class enables you to continuously call a delegate at specified time intervals. Этот класс также можно использовать, чтобы запланировать один вызов делегата через указанный интервал времени. You can also use this class to schedule a single call to a delegate in a specified time interval. Делегат выполняется в потоке ThreadPool. The delegate is executed on a ThreadPool thread.

При создании объекта System.Threading.Timer вы указываете делегат TimerCallback, который определяет метод обратного вызова, необязательный объект состояния, который передается обратному вызову, временную задержку до первого вызова обратного вызова и интервал времени между вызовами обратного вызова. When you create a System.Threading.Timer object, you specify a TimerCallback delegate that defines the callback method, an optional state object that is passed to the callback, the amount of time to delay before the first invocation of the callback, and the time interval between callback invocations. Чтобы отменить ожидающий таймер, вызовите метод Timer.Dispose. To cancel a pending timer, call the Timer.Dispose method.

В следующем примере создается таймер, который вызывает предоставленный делегат в первый раз через одну секунду (1000 миллисекунд), а затем каждые две секунды. The following example creates a timer that calls the provided delegate for the first time after one second (1000 milliseconds) and then calls it every two seconds. Объект состояния в примере используется для подсчета вызовов делегата. The state object in the example is used to count how many times the delegate is called. Таймер останавливается после 10 вызовов. The timer is stopped when the delegate has been called at least 10 times.

Timer Класс

Определение

Создает событие после заданного интервала с возможностью создания повторяющихся событий. Generates an event after a set interval, with an option to generate recurring events.

Примеры

В следующем примере создается экземпляр System.Timers.Timer объекта, который запускает Timer.Elapsed событие каждые две секунды (2 000 миллисекунд), настраивает обработчик событий для события и запускает таймер. The following example instantiates a System.Timers.Timer object that fires its Timer.Elapsed event every two seconds (2,000 milliseconds), sets up an event handler for the event, and starts the timer. Обработчик событий отображает значение ElapsedEventArgs.SignalTime свойства при каждом его возникновении. The event handler displays the value of the ElapsedEventArgs.SignalTime property each time it is raised.

Комментарии

TimerКомпонент является серверным таймером, который вызывает Elapsed событие в приложении после Interval истечения числа миллисекунд в свойстве. The Timer component is a server-based timer that raises an Elapsed event in your application after the number of milliseconds in the Interval property has elapsed. Можно настроить Timer объект для вызова события только один раз или многократно с помощью AutoReset Свойства. You can configure the Timer object to raise the event just once or repeatedly using the AutoReset property. Как правило, Timer объект объявляется на уровне класса, чтобы он оставался в области, пока он необходим. Typically, a Timer object is declared at the class level so that it stays in scope as long as it is needed. Затем можно обработать Elapsed событие, чтобы обеспечить нормальную обработку. You can then handle its Elapsed event to provide regular processing. Например, предположим, что имеется важный сервер, который должен храниться 24 часа в день, 7 дней в неделю. For example, suppose you have a critical server that must be kept running 24 hours a day, 7 days a week. Можно создать службу, которая использует Timer объект для периодической проверки сервера и обеспечения работоспособности системы. You could create a service that uses a Timer object to periodically check the server and ensure that the system is up and running. Если система не отвечает, служба может попытаться перезапустить сервер или уведомить администратора. If the system is not responding, the service could attempt to restart the server or notify an administrator.

TimerКласс доступен не для всех реализаций и версий .NET, например .NET Standard 1,6 и более ранних версий. The Timer class is not available for all .NET implementations and versions, such as .NET Standard 1.6 and lower versions. В этих случаях System.Threading.Timer вместо этого можно использовать класс. In these cases, you can use the System.Threading.Timer class instead.

Этот тип реализует интерфейс IDisposable. This type implements the IDisposable interface. По окончании использования выдаленную ему память следует прямо или косвенно освободить. When you have finished using the type, you should dispose of it either directly or indirectly. Чтобы сделать это прямо, вызовите его метод Dispose в блоке try / catch . To dispose of the type directly, call its Dispose method in a try / catch block. Чтобы сделать это косвенно, используйте языковые конструкции, такие как using (в C#) или Using (в Visual Basic). To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). Дополнительные сведения см. в разделе «Использование объекта, реализующего IDisposable» в статье об интерфейсе IDisposable. For more information, see the «Using an Object that Implements IDisposable» section in the IDisposable interface topic.

Серверный System.Timers.Timer класс предназначен для использования с рабочими потоками в многопоточной среде. The server-based System.Timers.Timer class is designed for use with worker threads in a multithreaded environment. Серверные таймеры могут перемещаться между потоками для решения возникшего Elapsed события, что приводит к большей точности, чем таймеры Windows при возникновении события вовремя. Server timers can move among threads to handle the raised Elapsed event, resulting in more accuracy than Windows timers in raising the event on time.

System.Timers.TimerКомпонент создает Elapsed событие на основе значения (в миллисекундах) Interval Свойства. The System.Timers.Timer component raises the Elapsed event, based on the value (in milliseconds) of the Interval property. Это событие можно обработать для выполнения необходимой обработки. You can handle this event to perform the processing you need. Например, предположим, что у вас есть интерактивное приложение для продаж, которое постоянно отправляет заказы на продажу в базу данных. For example, suppose that you have an online sales application that continuously posts sales orders to a database. Служба, которая компилирует инструкции для доставки, работает с пакетом заказов, вместо того чтобы обрабатывать каждый заказ по отдельности. The service that compiles the instructions for shipping operates on a batch of orders rather than processing each order individually. TimerДля запуска пакетной обработки каждые 30 минут можно использовать. You could use a Timer to start the batch processing every 30 minutes.

Читайте также:  Winrar для windows server

Класс System. Timers. Timer имеет то же разрешение, что и системные часы. The System.Timers.Timer class has the same resolution as the system clock. Это означает, что Elapsed событие будет срабатывать через интервал, определенный разрешением системных часов, если Interval свойство меньше, чем разрешение системных часов. This means that the Elapsed event will fire at an interval defined by the resolution of the system clock if the Interval property is less than the resolution of the system clock. Дополнительные сведения см. в описании свойства Interval. For more information, see the Interval property.

Если AutoReset для задано значение false , System.Timers.Timer объект создает Elapsed событие только один раз после первого Interval прохождения. When AutoReset is set to false , a System.Timers.Timer object raises the Elapsed event only once, after the first Interval has elapsed. Чтобы Elapsed регулярно вызывать событие через интервал, определенный параметром Interval , задайте AutoReset для true значение, которое является значением по умолчанию. To keep raising the Elapsed event regularly at the interval defined by the Interval, set AutoReset to true , which is the default value.

TimerКомпонент перехватывает и подавляет все исключения, вызываемые обработчиками событий для Elapsed события. The Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. Это поведение может быть изменено в будущих выпусках платформа .NET Framework. This behavior is subject to change in future releases of the .NET Framework. Однако обратите внимание, что это не относится к обработчикам событий, которые выполняются асинхронно и включают await оператор (в C#) или Await оператор (в Visual Basic). Note, however, that this is not true of event handlers that execute asynchronously and include the await operator (in C#) or the Await operator (in Visual Basic). Исключения, возникающие в этих обработчиках событий, передаются обратно в вызывающий поток, как показано в следующем примере. Exceptions thrown in these event handlers are propagated back to the calling thread, as the following example illustrates. Дополнительные сведения об исключениях, возникающих в асинхронных методах, см. в разделе обработка исключений. For more information on exceptions thrown in asynchronous methods, see Exception Handling.

Если SynchronizingObject свойство имеет значение null , Elapsed событие вызывается в ThreadPool потоке. If the SynchronizingObject property is null , the Elapsed event is raised on a ThreadPool thread. Если обработка Elapsed события длится дольше Interval , это событие может возникать снова в другом ThreadPool потоке. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. В этом случае обработчик событий должен быть повторным. In this situation, the event handler should be reentrant.

Метод обработки событий может выполняться в одном потоке в то же время, когда другой поток вызывает Stop метод или устанавливает Enabled свойство в значение false . The event-handling method might run on one thread at the same time that another thread calls the Stop method or sets the Enabled property to false . Это может привести к Elapsed возникновению события после остановки таймера. This might result in the Elapsed event being raised after the timer is stopped. В примере кода для Stop метода показан один из способов избежать этого состояния гонки. The example code for the Stop method shows one way to avoid this race condition.

Даже если SynchronizingObject параметр не равен null , Elapsed события могут происходить после Dispose Stop вызова метода или после того Enabled , как свойство имеет значение false , поскольку сигнал для вызова Elapsed события всегда находится в очереди на выполнение в потоке пула потоков. Even if SynchronizingObject is not null , Elapsed events can occur after the Dispose or Stop method has been called or after the Enabled property has been set to false , because the signal to raise the Elapsed event is always queued for execution on a thread pool thread. Одним из способов разрешения этого состояния гонки является установка флага, сообщающего обработчику событий о Elapsed пропуске последующих событий. One way to resolve this race condition is to set a flag that tells the event handler for the Elapsed event to ignore subsequent events.

Если System.Timers.Timer класс используется с элементом пользовательского интерфейса, таким как форма или элемент управления, без помещения таймера в этот элемент пользовательского интерфейса, назначьте форму или элемент управления, содержащий Timer SynchronizingObject свойство, так, чтобы событие было упаковано в поток пользовательского интерфейса. If you use the System.Timers.Timer class with a user interface element, such as a form or control, without placing the timer on that user interface element, assign the form or control that contains the Timer to the SynchronizingObject property, so that the event is marshaled to the user interface thread.

Список значений свойств по умолчанию для экземпляра Timer см. в разделе Timer конструктор. For a list of default property values for an instance of Timer, see the Timer constructor.

Имейте в виду, что в .NET есть четыре класса с именами Timer , каждый из которых предлагает различные функциональные возможности: Be aware that .NET includes four classes named Timer , each of which offers different functionality:

  • System.Timers.Timer (в этом разделе): запускает событие через регулярные интервалы. System.Timers.Timer (this topic): fires an event at regular intervals. Класс предназначен для использования в качестве серверного компонента или компонент службы в многопоточной среде. Он не имеет пользовательского интерфейса и не отображается во время выполнения. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer: выполняет один метод обратного вызова в потоке пула потоков через регулярные интервалы. System.Threading.Timer: executes a single callback method on a thread pool thread at regular intervals. Метод обратного вызова определяется при создании экземпляра таймера и не может быть изменен. The callback method is defined when the timer is instantiated and cannot be changed. Как и System.Timers.Timer класс, этот класс предназначен для использования в качестве серверного компонента или компонент службы в многопоточной среде; он не имеет пользовательского интерфейса и не отображается во время выполнения. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (Только платформа .NET Framework): компонент Windows Forms, который запускает событие через регулярные интервалы. System.Windows.Forms.Timer (.NET Framework only): a Windows Forms component that fires an event at regular intervals. У этого компонента нет интерфейса пользователя. Он предназначен для однопоточной среды. The component has no user interface and is designed for use in a single-threaded environment.
  • System.Web.UI.Timer (Только платформа .NET Framework): компонент ASP.NET, который выполняет асинхронные или синхронные обратные передачи веб-страниц через равные промежутки времени. System.Web.UI.Timer (.NET Framework only): an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
Читайте также:  Мониторинг операционной системы windows

Конструкторы

Инициализирует новый экземпляр класса Timer и задает всем свойствам начальные значения. Initializes a new instance of the Timer class, and sets all the properties to their initial values.

Инициализирует новый экземпляр класса Timer и задает свойству Interval указанное значение в миллисекундах. Initializes a new instance of the Timer class, and sets the Interval property to the specified number of milliseconds.

Свойства

Возвращает или задает логическое значение, определяющее, должен ли объект Timer вызывать событие Elapsed один раз ( false ) или неоднократно ( true ). Gets or sets a Boolean indicating whether the Timer should raise the Elapsed event only once ( false ) or repeatedly ( true ).

Возвращает значение, показывающее, может ли компонент вызывать событие. Gets a value indicating whether the component can raise an event.

(Унаследовано от Component) Container

Возвращает объект IContainer, который содержит коллекцию Component. Gets the IContainer that contains the Component.

(Унаследовано от Component) DesignMode

Возвращает значение, указывающее, находится ли данный компонент Component в режиме конструктора в настоящее время. Gets a value that indicates whether the Component is currently in design mode.

(Унаследовано от Component) Enabled

Возвращает или задает значение, определяющее, должен ли объект Timer вызывать событие Elapsed. Gets or sets a value indicating whether the Timer should raise the Elapsed event.

Возвращает список обработчиков событий, которые прикреплены к этому объекту Component. Gets the list of event handlers that are attached to this Component.

(Унаследовано от Component) Interval

Возвращает или задает интервал в миллисекундах, по истечении которого возникает событие Elapsed. Gets or sets the interval, expressed in milliseconds, at which to raise the Elapsed event.

Возвращает или задает сайт, который привязывает Timer к его контейнеру в режиме конструктора. Gets or sets the site that binds the Timer to its container in design mode.

Получает или задает объект, используемый для маршалирования вызовов обработчика событий, осуществленных после истечения интервала времени. Gets or sets the object used to marshal event-handler calls that are issued when an interval has elapsed.

Методы

Начинает во время выполнения инициализацию класса Timer, используемого в форме или другим компонентом. Begins the run-time initialization of a Timer that is used on a form or by another component.

Освобождает ресурсы, используемые объектом Timer. Releases the resources used by the Timer.

Создает объект, который содержит всю необходимую информацию для создания прокси-сервера, используемого для взаимодействия с удаленным объектом. Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Унаследовано от MarshalByRefObject) Dispose()

Освобождает все ресурсы, занятые модулем Component. Releases all resources used by the Component.

(Унаследовано от Component) Dispose(Boolean)

Освобождает все ресурсы, используемые текущим объектом Timer. Releases all resources used by the current Timer.

Заканчивает во время выполнения инициализацию класса Timer, используемого в форме или другим компонентом. Ends the run-time initialization of a Timer that is used on a form or by another component.

Определяет, равен ли указанный объект текущему объекту. Determines whether the specified object is equal to the current object.

(Унаследовано от Object) GetHashCode()

Служит хэш-функцией по умолчанию. Serves as the default hash function.

(Унаследовано от Object) GetLifetimeService()

Извлекает объект обслуживания во время существования, который управляет политикой времени существования данного экземпляра. Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) GetService(Type)

Возвращает объект, представляющий службу, предоставляемую классом Component или классом Container. Returns an object that represents a service provided by the Component or by its Container.

(Унаследовано от Component) GetType()

Возвращает объект Type для текущего экземпляра. Gets the Type of the current instance.

(Унаследовано от Object) InitializeLifetimeService()

Получает объект службы времени существования для управления политикой времени существования для этого экземпляра. Obtains a lifetime service object to control the lifetime policy for this instance.

(Унаследовано от MarshalByRefObject) MemberwiseClone()

Создает неполную копию текущего объекта Object. Creates a shallow copy of the current Object.

(Унаследовано от Object) MemberwiseClone(Boolean)

Создает неполную копию текущего объекта MarshalByRefObject. Creates a shallow copy of the current MarshalByRefObject object.

(Унаследовано от MarshalByRefObject) Start()

Начинает вызывать событие Elapsed, задавая для свойства Enabled значение true . Starts raising the Elapsed event by setting Enabled to true .

Прекращает вызывать событие Elapsed, задавая для свойства Enabled значение false . Stops raising the Elapsed event by setting Enabled to false .

Возвращает объект String, содержащий имя Component, если оно есть. Returns a String containing the name of the Component, if any. Этот метод не следует переопределять. This method should not be overridden.

(Унаследовано от Component)

События

Возникает при удалении компонента путем вызова метода Dispose(). Occurs when the component is disposed by a call to the Dispose() method.

(Унаследовано от Component) Elapsed

Происходит по истечении интервала времени. Occurs when the interval elapses.

Применяется к

Потокобезопасность

Все открытые static члены этого типа являются потокобезопасными. Any public static members of this type are thread safe. Потокобезопасная работа с членами экземпляров типа не гарантируется. Any instance members are not guaranteed to be thread safe.

Оцените статью