Timer Construtores
Definição
Importante
Algumas informações se referem a produtos de pré-lançamento que podem ser substancialmente modificados antes do lançamento. A Microsoft não oferece garantias, expressas ou implícitas, das informações aqui fornecidas.
Inicializa uma nova instância da classe Timer.
Sobrecargas
| Nome | Description |
|---|---|
| Timer(TimerCallback) |
Inicializa uma nova instância da Timer classe com um período infinito e um tempo de conclusão infinito, usando o objeto recém-criado Timer como o objeto de estado. |
| Timer(TimerCallback, Object, Int32, Int32) |
Inicializa uma nova instância da |
| Timer(TimerCallback, Object, Int64, Int64) |
Inicializa uma nova instância da |
| Timer(TimerCallback, Object, TimeSpan, TimeSpan) |
Inicializa uma nova instância da |
| Timer(TimerCallback, Object, UInt32, UInt32) |
Inicializa uma nova instância da |
Timer(TimerCallback)
public:
Timer(System::Threading::TimerCallback ^ callback);
public Timer(System.Threading.TimerCallback callback);
new System.Threading.Timer : System.Threading.TimerCallback -> System.Threading.Timer
Public Sub New (callback As TimerCallback)
Parâmetros
- callback
- TimerCallback
Um TimerCallback delegado que representa um método a ser executado.
Exemplos
O exemplo de código a seguir cria um novo temporizador, usando o temporizador em si como o objeto de estado. O Change método é usado para iniciar o temporizador. Quando o retorno de chamada do temporizador ocorre, o objeto de estado é usado para desativar o temporizador.
using System;
using System.Threading;
public class Example
{
public static void Main()
{
// Create an instance of the Example class, and start two
// timers.
Example ex = new Example();
ex.StartTimer(2000);
ex.StartTimer(1000);
Console.WriteLine("Press Enter to end the program.");
Console.ReadLine();
}
public void StartTimer(int dueTime)
{
Timer t = new Timer(new TimerCallback(TimerProc));
t.Change(dueTime, 0);
}
private void TimerProc(object state)
{
// The state object is the Timer object.
Timer t = (Timer) state;
t.Dispose();
Console.WriteLine("The timer callback executes.");
}
}
Imports System.Threading
Public Class Example
Public Shared Sub Main()
' Create an instance of the Example class, and start two
' timers.
Dim ex As New Example()
ex.StartTimer(2000)
ex.StartTimer(1000)
Console.WriteLine("Press Enter to end the program.")
Console.ReadLine()
End Sub
Public Sub StartTimer(ByVal dueTime As Integer)
Dim t As New Timer(AddressOf TimerProc)
t.Change(dueTime, 0)
End Sub
Private Sub TimerProc(ByVal state As Object)
' The state object is the Timer object.
Dim t As Timer = CType(state, Timer)
t.Dispose()
Console.WriteLine("The timer callback executes.")
End Sub
End Class
Comentários
Chame esse construtor quando quiser usar o Timer objeto em si como o objeto de estado. Depois de criar o temporizador, use o Change método para definir o intervalo e o tempo de conclusão.
Esse construtor especifica um tempo de conclusão infinito antes do primeiro retorno de chamada e um intervalo infinito entre retornos de chamada, a fim de impedir que o primeiro retorno de chamada ocorra antes que o Timer objeto seja atribuído ao objeto de estado.
O método especificado deve callback ser reentrant, pois é chamado em ThreadPool threads. O método pode ser executado simultaneamente em dois threads de pool de threads se o intervalo de temporizador for menor do que o tempo necessário para executar o método ou se todos os threads do pool de threads estiverem em uso e o método for enfileirado várias vezes.
Aplica-se a
Timer(TimerCallback, Object, Int32, Int32)
Inicializa uma nova instância da Timer classe, usando um inteiro com sinal de 32 bits para especificar o intervalo de tempo.
public:
Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, int dueTime, int period);
public Timer(System.Threading.TimerCallback callback, object state, int dueTime, int period);
new System.Threading.Timer : System.Threading.TimerCallback * obj * int * int -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As Integer, period As Integer)
Parâmetros
- callback
- TimerCallback
Um TimerCallback delegado que representa um método a ser executado.
- state
- Object
Um objeto que contém informações a serem usadas pelo método de retorno de chamada ou null.
- dueTime
- Int32
A quantidade de tempo para atrasar antes callback é invocada, em milissegundos. Especifique Infinite para impedir que o temporizador seja iniciado. Especifique zero (0) para iniciar o temporizador imediatamente.
- period
- Int32
O intervalo de tempo entre invocações de callback, em milissegundos. Especifique Infinite para desabilitar a sinalização periódica.
Exceções
O dueTime parâmetro ou o period parâmetro é negativo e não é igual a Infinite.
O callback parâmetro é null.
Exemplos
O exemplo de código a seguir mostra como criar um TimerCallback delegado e inicializar uma nova instância da Timer classe.
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
// Create an AutoResetEvent to signal the timeout threshold in the
// timer callback has been reached.
var autoEvent = new AutoResetEvent(false);
var statusChecker = new StatusChecker(10);
// Create a timer that invokes CheckStatus after one second,
// and every 1/4 second thereafter.
Console.WriteLine("{0:h:mm:ss.fff} Creating timer.\n",
DateTime.Now);
var stateTimer = new Timer(statusChecker.CheckStatus,
autoEvent, 1000, 250);
// When autoEvent signals, change the period to every half second.
autoEvent.WaitOne();
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period to .5 seconds.\n");
// When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne();
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
private int invokeCount;
private int maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal the waiting thread.
invokeCount = 0;
autoEvent.Set();
}
}
}
// The example displays output like the following:
// 11:59:54.202 Creating timer.
//
// 11:59:55.217 Checking status 1.
// 11:59:55.466 Checking status 2.
// 11:59:55.716 Checking status 3.
// 11:59:55.968 Checking status 4.
// 11:59:56.218 Checking status 5.
// 11:59:56.470 Checking status 6.
// 11:59:56.722 Checking status 7.
// 11:59:56.972 Checking status 8.
// 11:59:57.223 Checking status 9.
// 11:59:57.473 Checking status 10.
//
// Changing period to .5 seconds.
//
// 11:59:57.474 Checking status 1.
// 11:59:57.976 Checking status 2.
// 11:59:58.476 Checking status 3.
// 11:59:58.977 Checking status 4.
// 11:59:59.477 Checking status 5.
// 11:59:59.977 Checking status 6.
// 12:00:00.478 Checking status 7.
// 12:00:00.980 Checking status 8.
// 12:00:01.481 Checking status 9.
// 12:00:01.981 Checking status 10.
//
// Destroying timer.
Imports System.Threading
Public Module Example
Public Sub Main()
' Use an AutoResetEvent to signal the timeout threshold in the
' timer callback has been reached.
Dim autoEvent As New AutoResetEvent(False)
Dim statusChecker As New StatusChecker(10)
' Create a timer that invokes CheckStatus after one second,
' and every 1/4 second thereafter.
Console.WriteLine("{0:h:mm:ss.fff} Creating timer." & vbCrLf,
DateTime.Now)
Dim stateTimer As New Timer(AddressOf statusChecker.CheckStatus,
autoEvent, 1000, 250)
' When autoEvent signals, change the period to every half second.
autoEvent.WaitOne()
stateTimer.Change(0, 500)
Console.WriteLine(vbCrLf & "Changing period to .5 seconds." & vbCrLf)
' When autoEvent signals the second time, dispose of the timer.
autoEvent.WaitOne()
stateTimer.Dispose()
Console.WriteLine(vbCrLf & "Destroying timer.")
End Sub
End Module
Public Class StatusChecker
Dim invokeCount, maxCount As Integer
Sub New(count As Integer)
invokeCount = 0
maxCount = count
End Sub
' The timer callback method.
Sub CheckStatus(stateInfo As Object)
Dim autoEvent As AutoResetEvent = DirectCast(stateInfo, AutoResetEvent)
invokeCount += 1
Console.WriteLine("{0:h:mm:ss.fff} Checking status {1,2}.",
DateTime.Now, invokeCount)
If invokeCount = maxCount Then
' Reset the counter and signal the waiting thread.
invokeCount = 0
autoEvent.Set()
End If
End Sub
End Class
' The example displays output like the following:
' 11:59:54.202 Creating timer.
'
' 11:59:55.217 Checking status 1.
' 11:59:55.466 Checking status 2.
' 11:59:55.716 Checking status 3.
' 11:59:55.968 Checking status 4.
' 11:59:56.218 Checking status 5.
' 11:59:56.470 Checking status 6.
' 11:59:56.722 Checking status 7.
' 11:59:56.972 Checking status 8.
' 11:59:57.223 Checking status 9.
' 11:59:57.473 Checking status 10.
'
' Changing period to .5 seconds.
'
' 11:59:57.474 Checking status 1.
' 11:59:57.976 Checking status 2.
' 11:59:58.476 Checking status 3.
' 11:59:58.977 Checking status 4.
' 11:59:59.477 Checking status 5.
' 11:59:59.977 Checking status 6.
' 12:00:00.478 Checking status 7.
' 12:00:00.980 Checking status 8.
' 12:00:01.481 Checking status 9.
' 12:00:01.981 Checking status 10.
'
' Destroying timer.
Comentários
O delegado especificado pelo callback parâmetro é invocado uma vez após dueTime o decorrido e, depois disso, cada vez que o period intervalo de tempo passa.
Se dueTime for zero (0), callback será invocado imediatamente. Se dueTime for Timeout.Infinite, callback não for invocado; o temporizador será desabilitado, mas poderá ser habilitado novamente chamando o Change método.
Como a classe Timer tem a mesma resolução que o relógio do sistema, que tem aproximadamente 15 milissegundos em sistemas Windows 7 e Windows 8, o delegado callback é executado em intervalos definidos pela resolução do relógio do sistema se period for menor que a resolução do relógio do sistema. Se period for zero (0) ou Timeout.InfinitedueTime não Timeout.Infinitefor , callback será invocado uma vez; o comportamento periódico do temporizador será desabilitado, mas poderá ser reabilitado usando o Change método.
Note
O relógio do sistema usado é o mesmo relógio usado por GetTickCount, que não é afetado por alterações feitas com timeBeginPeriod e timeEndPeriod.
O método especificado deve callback ser reentrant, pois é chamado em ThreadPool threads. O método pode ser executado simultaneamente em dois threads de pool de threads se o intervalo de temporizador for menor do que o tempo necessário para executar o método ou se todos os threads do pool de threads estiverem em uso e o método for enfileirado várias vezes.
Confira também
Aplica-se a
Timer(TimerCallback, Object, Int64, Int64)
Inicializa uma nova instância da Timer classe, usando inteiros com sinal de 64 bits para medir intervalos de tempo.
public:
Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, long dueTime, long period);
public Timer(System.Threading.TimerCallback callback, object state, long dueTime, long period);
new System.Threading.Timer : System.Threading.TimerCallback * obj * int64 * int64 -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As Long, period As Long)
Parâmetros
- callback
- TimerCallback
Um TimerCallback delegado que representa um método a ser executado.
- state
- Object
Um objeto que contém informações a serem usadas pelo método de retorno de chamada ou null.
- dueTime
- Int64
A quantidade de tempo para atrasar antes callback é invocada, em milissegundos. Especifique Infinite para impedir que o temporizador seja iniciado. Especifique zero (0) para iniciar o temporizador imediatamente.
- period
- Int64
O intervalo de tempo entre invocações de callback, em milissegundos. Especifique Infinite para desabilitar a sinalização periódica.
Exceções
O dueTime parâmetro ou o period parâmetro é negativo e não é igual a Infinite.
O dueTime parâmetro ou o period parâmetro é maior que 4294967294.
Comentários
O delegado especificado pelo callback parâmetro é invocado uma vez após dueTime o decorrido e, depois disso, cada vez que o period intervalo de tempo passa.
Se dueTime for zero (0), callback será invocado imediatamente. Se dueTime for Timeout.Infinite, callback não for invocado; o temporizador será desabilitado, mas poderá ser habilitado novamente chamando o Change método.
Como a classe Timer tem a mesma resolução que o relógio do sistema, que tem aproximadamente 15 milissegundos em sistemas Windows 7 e Windows 8, o delegado callback é executado em intervalos definidos pela resolução do relógio do sistema se period for menor que a resolução do relógio do sistema.
Se period for zero (0) ou Timeout.InfinitedueTime não Timeout.Infinitefor , callback será invocado uma vez; o comportamento periódico do temporizador será desabilitado, mas poderá ser reabilitado usando o Change método.
Note
O relógio do sistema usado é o mesmo relógio usado por GetTickCount, que não é afetado por alterações feitas com timeBeginPeriod e timeEndPeriod.
O método especificado deve callback ser reentrant, pois é chamado em ThreadPool threads. O método pode ser executado simultaneamente em dois threads de pool de threads se o intervalo de temporizador for menor do que o tempo necessário para executar o método ou se todos os threads do pool de threads estiverem em uso e o método for enfileirado várias vezes.
Confira também
Aplica-se a
Timer(TimerCallback, Object, TimeSpan, TimeSpan)
Inicializa uma nova instância da Timer classe, usando TimeSpan valores para medir intervalos de tempo.
public:
Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, TimeSpan dueTime, TimeSpan period);
public Timer(System.Threading.TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period);
new System.Threading.Timer : System.Threading.TimerCallback * obj * TimeSpan * TimeSpan -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As TimeSpan, period As TimeSpan)
Parâmetros
- callback
- TimerCallback
Um delegado que representa um método a ser executado.
- state
- Object
Um objeto que contém informações a serem usadas pelo método de retorno de chamada ou null.
- dueTime
- TimeSpan
A quantidade de tempo a ser atrasada antes da callback invocação. Especifique InfiniteTimeSpan para impedir que o temporizador seja iniciado. Especifique Zero para iniciar o temporizador imediatamente.
- period
- TimeSpan
O intervalo de tempo entre invocações de callback. Especifique InfiniteTimeSpan para desabilitar a sinalização periódica.
Exceções
O número de milissegundos no valor de dueTime ou period é negativo e não igual a Infinite, ou é maior que Int32.MaxValue.
O callback parâmetro é null.
Exemplos
O exemplo de código a seguir mostra como criar um TimerCallback delegado e inicializar uma nova instância da Timer classe.
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(statusChecker.CheckStatus);
TimeSpan delayTime = new TimeSpan(0, 0, 1);
TimeSpan intervalTime = new TimeSpan(0, 0, 0, 0, 250);
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer = new Timer(
timerDelegate, autoEvent, delayTime, intervalTime);
// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(new TimeSpan(0),
intervalTime + intervalTime);
Console.WriteLine("\nChanging period.\n");
// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
int invokeCount, maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}
Imports System.Threading
Public Class TimerExample
<MTAThread> _
Shared Sub Main()
Dim autoEvent As New AutoResetEvent(False)
Dim statusChecker As New StatusChecker(10)
' Create the delegate that invokes methods for the timer.
Dim timerDelegate As TimerCallback = _
AddressOf statusChecker.CheckStatus
Dim delayTime As New TimeSpan(0, 0, 1)
Dim intervalTime As New TimeSpan(0, 0, 0, 0, 250)
' Create a timer that signals the delegate to invoke
' CheckStatus after one second, and every 1/4 second
' thereafter.
Console.WriteLine("{0} Creating timer." & vbCrLf, _
DateTime.Now.ToString("h:mm:ss.fff"))
Dim stateTimer As Timer = New Timer( _
timerDelegate, autoEvent, delayTime, intervalTime)
' When autoEvent signals, change the period to every
' 1/2 second.
autoEvent.WaitOne(5000, False)
stateTimer.Change( _
new TimeSpan(0), intervalTime.Add(intervalTime))
Console.WriteLine(vbCrLf & "Changing period." & vbCrLf)
' When autoEvent signals the second time, dispose of
' the timer.
autoEvent.WaitOne(5000, False)
stateTimer.Dispose()
Console.WriteLine(vbCrLf & "Destroying timer.")
End Sub
End Class
Public Class StatusChecker
Dim invokeCount, maxCount As Integer
Sub New(count As Integer)
invokeCount = 0
maxCount = count
End Sub
' This method is called by the timer delegate.
Sub CheckStatus(stateInfo As Object)
Dim autoEvent As AutoResetEvent = _
DirectCast(stateInfo, AutoResetEvent)
invokeCount += 1
Console.WriteLine("{0} Checking status {1,2}.", _
DateTime.Now.ToString("h:mm:ss.fff"), _
invokeCount.ToString())
If invokeCount = maxCount Then
' Reset the counter and signal to stop the timer.
invokeCount = 0
autoEvent.Set()
End If
End Sub
End Class
Comentários
O delegado especificado pelo callback parâmetro é invocado uma vez após dueTime o decorrido e, depois disso, cada vez que o period intervalo de tempo passa.
Se dueTime for zero (0), callback será invocado imediatamente. Se dueTime for negativo um (-1) milissegundos, callback não será invocado; o temporizador será desabilitado, mas poderá ser habilitado novamente chamando o Change método.
Como a classe Timer tem a mesma resolução que o relógio do sistema, que tem aproximadamente 15 milissegundos em sistemas Windows 7 e Windows 8, o delegado callback é executado em intervalos definidos pela resolução do relógio do sistema se period for menor que a resolução do relógio do sistema. Se period for zero (0) ou negativo (-1) milissegundos e dueTime for positivo, callback será invocado uma vez; o comportamento periódico do temporizador será desabilitado, mas poderá ser reabilitado usando o Change método.
Note
O relógio do sistema usado é o mesmo relógio usado por GetTickCount, que não é afetado por alterações feitas com timeBeginPeriod e timeEndPeriod.
O método especificado deve callback ser reentrant, pois é chamado em ThreadPool threads. O método pode ser executado simultaneamente em dois threads de pool de threads se o intervalo de temporizador for menor do que o tempo necessário para executar o método ou se todos os threads do pool de threads estiverem em uso e o método for enfileirado várias vezes.
Confira também
Aplica-se a
Timer(TimerCallback, Object, UInt32, UInt32)
Importante
Esta API não está em conformidade com CLS.
Inicializa uma nova instância da Timer classe, usando inteiros sem sinal de 32 bits para medir intervalos de tempo.
public:
Timer(System::Threading::TimerCallback ^ callback, System::Object ^ state, System::UInt32 dueTime, System::UInt32 period);
[System.CLSCompliant(false)]
public Timer(System.Threading.TimerCallback callback, object state, uint dueTime, uint period);
[<System.CLSCompliant(false)>]
new System.Threading.Timer : System.Threading.TimerCallback * obj * uint32 * uint32 -> System.Threading.Timer
Public Sub New (callback As TimerCallback, state As Object, dueTime As UInteger, period As UInteger)
Parâmetros
- callback
- TimerCallback
Um delegado que representa um método a ser executado.
- state
- Object
Um objeto que contém informações a serem usadas pelo método de retorno de chamada ou null.
- dueTime
- UInt32
A quantidade de tempo para atrasar antes callback é invocada, em milissegundos. Especifique Infinite para impedir que o temporizador seja iniciado. Especifique zero (0) para iniciar o temporizador imediatamente.
- period
- UInt32
O intervalo de tempo entre invocações de callback, em milissegundos. Especifique Infinite para desabilitar a sinalização periódica.
- Atributos
Exceções
O dueTime parâmetro ou o period parâmetro é negativo e não é igual a Infinite.
O callback parâmetro é null.
Comentários
O delegado especificado pelo callback parâmetro é invocado uma vez após dueTime o decorrido e, depois disso, cada vez que o period intervalo de tempo passa.
Se dueTime for zero (0), callback será invocado imediatamente. Se dueTime for Timeout.Infinite, callback não for invocado; o temporizador será desabilitado, mas poderá ser habilitado novamente chamando o Change método.
Como a classe Timer tem a mesma resolução que o relógio do sistema, que tem aproximadamente 15 milissegundos em sistemas Windows 7 e Windows 8, o delegado callback é executado em intervalos definidos pela resolução do relógio do sistema se period for menor que a resolução do relógio do sistema. Se period for zero (0) ou Timeout.InfinitedueTime não Timeout.Infinitefor , callback será invocado uma vez; o comportamento periódico do temporizador será desabilitado, mas poderá ser reabilitado usando o Change método.
Note
O relógio do sistema usado é o mesmo relógio usado por GetTickCount, que não é afetado por alterações feitas com timeBeginPeriod e timeEndPeriod.
O método especificado deve callback ser reentrant, pois é chamado em ThreadPool threads. O método pode ser executado simultaneamente em dois threads de pool de threads se o intervalo de temporizador for menor do que o tempo necessário para executar o método ou se todos os threads do pool de threads estiverem em uso e o método for enfileirado várias vezes.