Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Classe Timer

 

Publicado: agosto de 2016

Fornece um mecanismo para executar um método em um thread do pool de threads aos intervalos especificados. Essa classe não pode ser herdada.

Para procurar esse tipo no código-fonte do .NET Framework, consulte a Reference Source (Fonte de referência).

Namespace:   System.Threading
Assembly:  mscorlib (em mscorlib.dll)

System.Object
  System.MarshalByRefObject
    System.Threading.Timer

[ComVisibleAttribute(true)]
[HostProtectionAttribute(SecurityAction.LinkDemand, Synchronization = true, 
	ExternalThreading = true)]
public sealed class Timer : MarshalByRefObject, IDisposable

NomeDescrição
System_CAPS_pubmethodTimer(TimerCallback)

Inicializa uma nova instância da classe Timer com um período infinito e um tempo de validade infinito usando o objeto Timer recém-criado como o objeto de estado.

System_CAPS_pubmethodTimer(TimerCallback, Object, Int32, Int32)

Inicializa uma nova instância da classe Timer, usando um inteiro com sinal de 32 bits para especificar o intervalo de tempo.

System_CAPS_pubmethodTimer(TimerCallback, Object, Int64, Int64)

Inicializa uma nova instância da classe Timer, usando um inteiro com sinal de 64 bits para medir intervalos de tempo.

System_CAPS_pubmethodTimer(TimerCallback, Object, TimeSpan, TimeSpan)

Inicializa uma nova instância da classe Timer, usando valores TimeSpan para medir intervalos de tempo.

System_CAPS_pubmethodTimer(TimerCallback, Object, UInt32, UInt32)

Inicializa uma nova instância da classe Timer, usando inteiros sem sinal de 32 bits para medir os intervalos de tempo.

NomeDescrição
System_CAPS_pubmethodChange(Int32, Int32)

Altera a hora de início e o intervalo entre as invocações de método para um temporizador, usando inteiros com sinal de 32 bits para medir intervalos de tempo.

System_CAPS_pubmethodChange(Int64, Int64)

Altera a hora de início e o intervalo entre as invocações de método para um temporizador, usando inteiros com sinal de 64 bits para medir intervalos de tempo.

System_CAPS_pubmethodChange(TimeSpan, TimeSpan)

Altera a hora de início e o intervalo entre as invocações de método para um temporizador, usando valores de TimeSpan para medir os intervalos de tempo.

System_CAPS_pubmethodChange(UInt32, UInt32)

Altera a hora de início e o intervalo entre as invocações de método de um temporizador, usando inteiros sem sinal de 32 bits para medir os intervalos de tempo.

System_CAPS_pubmethodCreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.(Herdado de MarshalByRefObject.)

System_CAPS_pubmethodDispose()

Libera todos os recursos usados pela instância atual do Timer.

System_CAPS_pubmethodDispose(WaitHandle)

Libera todos os recursos usados pela instância atual do Timer e indica quando o temporizador for descartado.

System_CAPS_pubmethodEquals(Object)

Verifica se o objeto especificado é igual ao objeto atual. (Herdado de Object.)

System_CAPS_pubmethodGetHashCode()

Serve como a função de hash padrão.(Herdado de Object.)

System_CAPS_pubmethodGetLifetimeService()

Recupera o objeto atual de serviço de vida útil que controla a diretiva de vida útil para esta instância. (Herdado de MarshalByRefObject.)

System_CAPS_pubmethodGetType()

Obtém o Type da instância atual.(Herdado de Object.)

System_CAPS_pubmethodInitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a diretiva de vida útil para esta instância. (Herdado de MarshalByRefObject.)

System_CAPS_pubmethodToString()

Retorna uma string que representa o objeto atual.(Herdado de Object.)

System_CAPS_noteObservação

To view the .NET Framework source code for this type, see the Reference Sourcehttp://referencesource.microsoft.com/#mscorlib/system/threading/timer.cs#051a39d380760b26. You can browse through the source code online, download the reference for offline viewing, and step through the sources (including patches and updates) during debugging; see instructionshttp://referencesource.microsoft.com/.

Use a T:System.Threading.TimerCallback delegate to specify the method you want the T:System.Threading.Timer to execute. The signature of the T:System.Threading.TimerCallback delegate is:

void TimerCallback(Object state)

The timer delegate is specified when the timer is constructed, and cannot be changed. The method does not execute on the thread that created the timer; it executes on a T:System.Threading.ThreadPool thread supplied by the system.

System_CAPS_tipDica

The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks 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, which 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. 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, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.

  • System.Web.UI.Timer, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

When you create a timer, you can specify an amount of time to wait before the first execution of the method (due time), and an amount of time to wait between subsequent executions (period). The T:System.Threading.Timer class has the same resolution as the system clock. This means that if the period is less than the resolution of the system clock, the T:System.Threading.TimerCallback delegate will execute at intervals defined by the resolution of the system clock, which is approximately 15 milliseconds on Windows 7 and Windows 8 systems. You can change the due time and period, or disable the timer, by using the M:System.Threading.Timer.Change(System.Int32,System.Int32) method.

System_CAPS_noteObservação

As long as you are using a T:System.Threading.Timer, you must keep a reference to it. As with any managed object, a T:System.Threading.Timer is subject to garbage collection when there are no references to it. The fact that a T:System.Threading.Timer is still active does not prevent it from being collected.

When a timer is no longer needed, use the Overload:System.Threading.Timer.Dispose method to free the resources held by the timer. Note that callbacks can occur after the M:System.Threading.Timer.Dispose method overload has been called, because the timer queues callbacks for execution by thread pool threads. You can use the M:System.Threading.Timer.Dispose(System.Threading.WaitHandle) method overload to wait until all callbacks have completed.

The callback method executed by the timer should be reentrant, because it is called on T:System.Threading.ThreadPool threads. The callback can be executed simultaneously on two thread pool threads if the timer interval is less than the time required to execute the callback, or if all thread pool threads are in use and the callback is queued multiple times.

System_CAPS_noteObservação

System.Threading.Timer is a simple, lightweight timer that uses callback methods and is served by thread pool threads. It is not recommended for use with Windows Forms, because its callbacks do not occur on the user interface thread. System.Windows.Forms.Timer is a better choice for use with Windows Forms. For server-based timer functionality, you might consider using System.Timers.Timer, which raises events and has additional features.

The following example defines a StatusChecker class that includes a CheckStatus method whose signature is the same as the T:System.Threading.TimerCallback delegate. The state argument of the CheckStatus method is an T:System.Threading.AutoResetEvent object that is used to synchronize the application thread and the thread pool thread that executes the callback delegate. The StatusChecker class also includes two state variables:

invokeCount

Indicates the number of times the callback method has been invoked.

maxCount

Determines the maximum number of times the callback method should be invoked.

The application thread creates the timer, which waits one second and then executes the CheckStatus callback method every 250 milliseconds. The application thread then blocks until the T:System.Threading.AutoResetEvent object is signaled. When the CheckStatus callback method executes maxCount times, it calls the AutoResetEvent.Set method to set the state of the T:System.Threading.AutoResetEvent object to signaled. The first time this happens, the application thread calls the M:System.Threading.Timer.Change(System.Int32,System.Int32) method so that the callback method now executes every half second. It once again blocks until the T:System.Threading.AutoResetEvent object is signaled. When this happens, the timer is destroyed by calling its M:System.Threading.Timer.Dispose method, and the application terminates.

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.

Plataforma Universal do Windows
Disponível desde 8.1
.NET Framework
Disponível desde 1.1
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1

This type is thread safe.

Retornar ao início
Mostrar: