[英]c# timer.elapsed?
我已經包含了System.Timers
包,但是當我輸入:
Timer.Elapsed; //its not working, the property elapsed is just not there.
我記得它在 VB.NET 中。 為什么這不起作用?
它不是財產。 這是一個事件。
因此,您必須提供一個事件處理程序,該處理程序將在每次計時器滴答時執行。 像這樣的東西:
public void CreateTimer()
{
var timer = new System.Timers.Timer(1000); // fire every 1 second
timer.Elapsed += HandleTimerElapsed;
}
public void HandleTimerElapsed(object sender, ElapsedEventArgs e)
{
// do whatever it is that you need to do on a timer
}
微軟的例子。 http://msdn.microsoft.com/en-us/library/system.timers.timer.elapsed.aspx
Elapsed 是一個事件,因此需要一個事件處理程序。
using System;
using System.Timers;
public class Timer1
{
private static System.Timers.Timer aTimer;
public static void Main()
{
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
/* This code example produces output similar to the following:
Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
*/
這里之前的答案都是正確的,但是現在 .net 6 / VS2022 已經發布並且關於可空性很重要,並且所有上述答案都會引發編譯器警告 CS8622。
解決方案是在回調函數的參數中簡單地將源對象標記為可為空,如下所示:
...
var timer = new System.Timers.Timer(2000); // every 2000ms
timer.Elapsed += TimerElapsedHandler;
...
public void TimerElapsedHandler(object? source, ElapsedEventArgs e)
{
//Your Handling Code Here
}
您需要一個事件處理程序,然后在分配事件處理程序時啟用並在您的處理程序中停止一個條件
Timer = new System.Timers.Timer();
Timer.Elapsed += new System.Timers.ElapsedEventHandler(PageLoaded);
Timer.Interval = 3000;
Timer.Enabled = true;
.....................
public void PageLoaded(object source, System.Timers.ElapsedEventArgs e)
{
// Do what ever here
if (StopCondition)Timer.Enabled = false;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.