我不知道我的标题是否非常具体,但我的问题是我想等待1秒(1000毫秒)来执行方法上的操作。我之前没有使用过Timer,但我发现你做了类似的事情:
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
然后定义OnTimedEvent方法:
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
关键是我想调用的方法接收5个参数,我见过的所有例子都使用了对象源,ElapsedEventArgs e。我想知道如何调用方法并在1秒后发送它的参数。 非常感谢你!
答案 0 :(得分:1)
使用
创建一个小助手类现在实例化它,分配参数并将包装器方法设置为计时器委托。
答案 1 :(得分:0)
问题是......
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
MyMethod(par1, par2, parn..);
}
答案 2 :(得分:0)
您是否考虑过延长计时器以达到您想要的效果?以下是一些示例代码:
class Program
{
static void Main(string[] args)
{
TimerEx timer = new TimerEx(1000, 1, 2, 3, 4, 5);
timer.ElapsedEx += new ElapsedExEventHandler(timer_ElapsedEx);
timer.Start();
Console.ReadKey();
}
static void timer_ElapsedEx(object sender, ElapsedEventArgsEx e)
{
Console.WriteLine(e.P1.ToString());
}
public delegate void ElapsedExEventHandler(object sender, ElapsedEventArgsEx e);
public class TimerEx : System.Timers.Timer
{
private ElapsedEventArgsEx e;
public TimerEx(double interval, object p1, object p2, object p3, object p4, object p5) : base(interval)
{
e = new ElapsedEventArgsEx() { P1 = p1, P2 = p2, P3 = p3, P4 = p4, P5 = p5 };
this.Elapsed += new ElapsedEventHandler(TimerEx_Elapsed);
}
void TimerEx_Elapsed(object sender, ElapsedEventArgs e)
{
this.OnElapsedEx(e.SignalTime);
}
public event ElapsedExEventHandler ElapsedEx;
private void OnElapsedEx(DateTime signalTime)
{
var handler = this.ElapsedEx;
if (handler != null)
{
e.SignalTime = signalTime;
handler(this, e);
}
}
}
public class ElapsedEventArgsEx : EventArgs
{
public ElapsedEventArgsEx()
{
}
public DateTime SignalTime { get; set; }
public object P1 { get; set; }
public object P2 { get; set; }
public object P3 { get; set; }
public object P4 { get; set; }
public object P5 { get; set; }
}
}
答案 3 :(得分:0)
您可以使用匿名代表。
Lambda语法是制作一个
的最简单方法aTimer.Elapsed += (source, args) => OnTimedEvent(source, args, extraarg1, extraarg2 /* etc */);
但您也可以使用旧语法:
aTimer.Elapsed += delegate (object source, ElapsedEventArgs args) { OnTimedEvent(source, args, extraarg1, extraarg2 /* etc */); };