根据函数执行时间设置定时器间隔
问题描述:
如何根据函数的执行时间量将定时器设置为间隔。根据函数执行时间设置定时器间隔
int main()
{
Timer t=new Timer();
t.start();
myfunc();
t.stop();
long elapsed=stop-start;
Need to set timer to this interval everytime instead of fixed interval.
}
答
最好的办法是使用StopWatch Class,它提供了一套可用于精确测量经过时间的方法和属性。有些事情是这样的:
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
// Do something
myfunc();
// Stop timing
stopwatch.Stop();
// Write result
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
答
class Myclass
{
private static Timer newTimer;
static void main()
{
newTimer=new Timer(timercallback,null,0,10000);
}
private static timercallback(Object o)
{
Stopwatch sw=new Stopwatch();
sw.Start();
myfunction();
sw.Stop();
newTimer.change(0,sw.ElapsedMilliseconds);
GC.Collect();
//这将设置基于函数执行时间的计时器间隔。 }
你想通过这样做达到什么目的?这是为什么? – Enigmativity 2012-07-15 08:34:00
需要一次又一次地调用我的函数,而不是一次提供固定的时间间隔,为什么不根据我的函数执行的时间量来设置时间间隔。此外,我的函数从数据库中检索不断更新的记录,因此执行时间将随时间而变化。 – user1502952 2012-07-15 08:51:21
为什么不只是异步地运行任务?不需要定时器。 – Enigmativity 2012-07-15 09:43:20