ElapsedEventArgs.SignalTime Свойство

Определение

Возвращает дату и время возникновения события Elapsed.

public:
 property DateTime SignalTime { DateTime get(); };
public DateTime SignalTime { get; }
member this.SignalTime : DateTime
Public ReadOnly Property SignalTime As DateTime

Значение свойства

Elapsed Время возникновения события.

Примеры

В следующем примере создается экземпляр объекта, который запускает событие Timer каждые две секунды (2000 миллисекунд), настраивает Timer.Elapsed обработчик событий для события и запускает таймер. Обработчик событий отображает значение ElapsedEventArgs.SignalTime свойства при каждом вызове.

using System;
using System.Timers;

public class Example
{
    private static Timer aTimer;

    public static void Main()
    {
        // Create a timer and set a two second interval.
        aTimer = new System.Timers.Timer();
        aTimer.Interval = 2000;

        // Hook up the Elapsed event for the timer. 
        aTimer.Elapsed += OnTimedEvent;

        // Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = true;

        // Start the timer
        aTimer.Enabled = true;

        Console.WriteLine("Press the Enter key to exit the program at any time... ");
        Console.ReadLine();
    }

    private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    }
}
// The example displays output like the following: 
//       Press the Enter key to exit the program at any time... 
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM
open System.Timers

let onTimedEvent source (e: ElapsedEventArgs) =
    printfn $"The Elapsed event was raised at {e.SignalTime}"

// Create a timer and set a two second interval.
let aTimer = new Timer()
aTimer.Interval <- 2000

// Hook up the Elapsed event for the timer. 
aTimer.Elapsed.AddHandler onTimedEvent

// Have the timer fire repeated events (true is the default)
aTimer.AutoReset <- true

// Start the timer
aTimer.Enabled <- true

printfn "Press the Enter key to exit the program at any time... "
stdin.ReadLine() |> ignore

// The example displays output like the following: 
//       Press the Enter key to exit the program at any time... 
//       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
//       The Elapsed event was raised at 5/20/2015 8:49:06 PM
Imports System.Timers

Public Module Example
    Private aTimer As Timer

    Public Sub Main()
        ' Create a timer and set a two second interval.
        aTimer = New System.Timers.Timer()
        aTimer.Interval = 2000

        ' Hook up the Elapsed event for the timer.  
        AddHandler aTimer.Elapsed, AddressOf OnTimedEvent

        ' Have the timer fire repeated events (true is the default)
        aTimer.AutoReset = True

        ' Start the timer
        aTimer.Enabled = True

        Console.WriteLine("Press the Enter key to exit the program at any time... ")
        Console.ReadLine()
    End Sub

    Private Sub OnTimedEvent(source As Object, e As System.Timers.ElapsedEventArgs)
        Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime)
    End Sub
End Module
' The example displays output like the following: 
'       Press the Enter key to exit the program at any time... 
'       The Elapsed event was raised at 5/20/2015 8:48:58 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:00 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:02 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:04 PM 
'       The Elapsed event was raised at 5/20/2015 8:49:06 PM

Комментарии

Событие Timer.Elapsed вызывается в потоке ThreadPool , поэтому метод обработки событий может выполняться в одном потоке одновременно, когда вызов Timer.Stop метода выполняется в другом потоке. Это может привести к Elapsed возникновению события после Stop вызова метода. Это условие гонки нельзя предотвратить просто путем сравнения SignalTime свойства с временем Stop вызова метода, так как метод обработки событий уже может выполняться при Stop вызове метода или может начать выполняться между моментом Stop вызова метода и моментом сохранения времени остановки. Если важно предотвратить выполнение потока, вызывающего Stop метод, пока метод обработки событий по-прежнему выполняется, используйте более надежный механизм синхронизации, Monitor например класс или CompareExchange метод. Код, использующий CompareExchange метод, можно найти в примере для Timer.Stop метода.

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

См. также раздел