[英]Raise event from one class to another
所以我想开始检查我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();
但这仍然有帮助。
等待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();
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.