所以我想从我的class
开始检查时间,当time
通过时(1分钟)我想提出事件:
public class TimeOut
{
private readonly int TIME_OUT = 60;
private System.Timers.Timer _timer;
private Stopwatch _stopwatch;
public event TimeOutHandler TimePassed;
public void Initiate()
{
_timer = new System.Timers.Timer();
_timer.Interval = 1000;
_timer.Elapsed += _timer_Elapsed;
_stopwatch = new Stopwatch();
}
public void Start()
{
_stopwatch.Start();
_timer.Start();
}
public void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (_stopwatch.ElapsedMilliseconds / 1000 >= TIME_OUT)
{
if (TimePassed!=null)
{
TimePassed(sender, null);
Stop();
}
}
}
public void Stop()
{
_timer.Stop();
_stopwatch.Stop();
}
}
用法
TimeOut timeOut = new TimeOut();
timeOut.TimePassed += timeOut_TimePassed;
timeOut.Initiate();
timeOut.Start();
private void timeOut_TimePassed(object sener, System.EventArgs e)
{
}
所以我不知道为什么,但似乎我的timer elapsed
函数从未启动过。
我尝试_timer.Enabled = true;
代替_timer.Start();
,但现在仍有帮助。
答案 0 :(得分:0)
等了1分钟后,它为我打了电话。
但是,你的代码只是从复制和粘贴中编译而来。将事件更改为委托,我必须使您的私有方法保持静态。
也不确定问题的最后一点,但至少在我的情况下,控制台立即关闭。所以我在最后添加了Console.Read()以等待计时器过去。 var x仅用于断点
希望这有帮助
using System;
using System.Diagnostics;
using System.Linq;
using System.Collections.Generic;
using System.Timers;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
TimeOut timeOut = new TimeOut();
timeOut.TimePassed += timeOut_TimePassed;
timeOut.Initiate();
timeOut.Start();
Console.Read();
}
// Changed this
private static void timeOut_TimePassed(object sener, System.EventArgs e)
{
var x = 1;
}
}
public class TimeOut
{
private readonly int TIME_OUT = 60;
private System.Timers.Timer _timer;
private Stopwatch _stopwatch;
// Changed this
public delegate void TimeOutHandler(object sener, EventArgs e);
public event TimeOutHandler TimePassed;
public void Initiate()
{
_timer = new System.Timers.Timer();
_timer.Interval = 1000;
_timer.Elapsed += _timer_Elapsed;
_stopwatch = new Stopwatch();
}
public void Start()
{
_stopwatch.Start();
_timer.Start();
}
public void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (_stopwatch.ElapsedMilliseconds / 1000 >= TIME_OUT)
{
if (TimePassed != null)
{
TimePassed(sender, null);
Stop();
}
}
}
public void Stop()
{
_timer.Stop();
_stopwatch.Stop();
}
}
}