我有5个方法,我需要在随机间隔(1到3秒)后调用它们。假设第一个方法在1秒后调用,第二个方法在2.3秒后调用,下一个方法在1.5秒后调用,依此类推。
System.Windows.Forms.Timer mytimer = new System.Windows.Forms.Timer();
mytimer.Tick += new EventHandler(TimerEventProcessor);    
Random rand = new Random();
int fortimerinterval = rand.Next(1000, 3000);
mytimer.Interval = fortimerinterval; 
mytimer.Enabled = true;
mytimer.Start();
    public void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
    {
        fortimerinterval = rand.Next(1000, 3000);
        mytimer.Interval = fortimerinterval; 
        first time call function1, then call function2
        //this is main theme, so im not giving whole code here
    }但在获得第一个随机值后,计时器间隔保持不变。似乎,每次调用TimerEventProcessor时,timerinterval值都不会改变。我该怎么做呢?或者是否有任何其他简单的方法来做到这一点。谢谢
发布于 2013-04-01 14:39:14
我对你的代码做了一些修改,并尝试了一下。它工作得很好。
Random rand = new Random();
Timer mytimer = new Timer();
private void fireTimerClick(object sender, EventArgs e)
{
    mytimer.Tick += new EventHandler(TimerEventProcessor);
    mytimer.Interval = rand.Next(1000, 3000);
    mytimer.Enabled = true;
    mytimer.Start();
}
public void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
    mytimer.Interval = rand.Next(1000, 3000);
    System.Diagnostics.Debug.WriteLine(DateTime.Now);
}您可以使用“调试输出”窗口验证这一点。fireTimerClick只是一个按钮单击事件处理程序。
https://stackoverflow.com/questions/15738656
复制相似问题