在第一个计时器的一半时间内完成一个事件?

时间:2014-05-05 22:49:49

标签: c#

所以我想要做的基本上是..有2个事件,让我们称这些事件1和事件2,当事件1开始时,计时器被激活,当它结束时(金额每次变化) ,它将经过的时间存储到双变量

(到目前为止,它的编码都很好)

但我的问题是..我希望事件2运行的时间是事件1的一半。因此我决定将此值存储在另一个双变量中,并将值除以2 ..

从这里开始我想要设置一种'倒数计时器'这样一旦从存储了一半时间的双变量到期时间,事件就会停止。

这是我到目前为止所拥有的......

//Creation of timer
Stopwatch Timer1 = new Stopwatch();

//Start the timer
Timer1.Start();

//Event 1 carries out here.. (Ain't going to bore you with this code)

//(Once ended) (ends once a condition is matched.. but cutting it short)..
//Timer1.Stop();

//Store amount in a double variable..
double dfull = Timer1.ElapsedMilliseconds;

//Half the amount in variable dhalf
double dhalf;
dhalf = dfull / 2;

//From here I want EVENT 2 to perform for the time stored in dC2B

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容执行此操作

System.Timers.Timer readyUpTimer = new System.Timers.Timer(100);
readyUpTimer.Elapsed -= readyUpTimer_Elapsed;
readyUpTimer.Elapsed += readyUpTimer_Elapsed;
DateTime readyUpInitialised = DateTime.Now;
readyUpTimer.Start();

然后在你的事件处理程序

void readyUpTimer_Elapsed(object sender, ElapsedEventArgs e)
{
   TimeSpan elapsed = DateTime.Now - this.readyUpInitialised;
   if (elapsed.TotalMilliseconds > dhalf)
   {
      readyUpTimer.Stop();
      readyUpTimer.Dispose();
      // Do other things...
   }
}

我希望这会有所帮助。