我正在使用System.Timers.Timer
该类创建一个带有Timer.Elapsed
事件的计时器.事情是Timer.Elapsed
只有在间隔时间过去之后才会首次触发事件.
有没有办法Timer.Elapsed
在启动计时器后立即举起活动?
我在System.Timers.Timer
课堂上找不到任何相关的财产.
Geo*_*ett 30
只需Timer_Tick
自己调用方法即可.
如果您不想处理Tick回调方法的参数,那么只需将您的代码Timer_Tick
放入另一个方法中,然后从Timer_Tick调用它,并从Timer.Start()
调用后调用
正如@Yahia所指出的那样,你也可以使用System.Threading.Timer
定时器,你可以将其设置为初始延迟为0.但是要注意,回调将在不同的线程上运行,而不是在Windows.Forms.Timer
运行的回调上运行UI线程.因此,如果您使用System.Threading.Timer
(无需正确调用)更新任何UI控件,它将崩溃.
Yah*_*hia 11
不确定,System.Timers.Timer
但试试
System.Threading.Timer T = new System.Threading.Timer(new TimerCallback(DoSomething), null, 0, 30000);
Run Code Online (Sandbox Code Playgroud)
这立即开始(第一次运行为0毫秒,后续运行为30000毫秒)......
请参阅
http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx
http://msdn.microsoft.com/en-us/library/2x96zfy7.aspx
Joh*_*dom 11
我知道这个答案很晚但是如果你希望你System.Timers.Timer
在100毫秒(默认间隔)内被解雇,那么你只需要在Timer
没有指定间隔的情况下初始化对象,然后将被调用函数内的间隔设置为你喜欢的任何内容.以下是我在Windows服务中使用的示例:
private static Timer _timer;
protected override void OnStart(string[] args)
{
_timer = new Timer(); //This will set the default interval
_timer.AutoReset = false;
_timer.Elapsed = OnTimer;
_timer.Start();
}
private void OnTimer(object sender, ElapsedEventArgs args)
{
//Do some work here
_timer.Stop();
_timer.Interval = 50000; //Set your new interval here
_timer.Start();
}
Run Code Online (Sandbox Code Playgroud)
第一次,计时器将在 1 秒后启动。之后,它的间隔将更改为每 30 秒或其他......
//main function
Timer timer = new Timer(1000); //initial start after 1 second
timer.Elapsed += new ElapsedEventHandler(TimerElapsedMethod);
timer.Start();
}
private void TimerElapsedMethod(object sender, ElapsedEventArgs e)
{
Timer timer = (Timer)sender; // Get the timer that fired the event
timer.Interval = 30000; // Change the interval to whatever
.
.
.
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
64553 次 |
最近记录: |