我有问题。我创建了两个Timer对象,一个在每个设定的时间段运行一些方法,第二个对象改变那个时间。问题是:当我尝试从第二个计时器更改第一个计时器的间隔时,我不想在方法更改时运行第一个计时器。
我有以下代码,有人可能会指出我正确的方向吗?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public void someFun1(Object obj)
{
Console.WriteLine("Start1 " + DateTime.Now);
}
public void changeTime1(Object obj)
{
someTime1.Change(0, 2000);
}
public static TimerCallback somedel1;
public static Timer someTime1;
public static TimerCallback changeTimedel1;
public static Timer changerTimer1;
static void Main(string[] args)
{
Program pr = new Program();
somedel1 = new TimerCallback(pr.someFun1);
someTime1 = new Timer(somedel1, null, Timeout.Infinite, 10000 );
changeTimedel1 = new TimerCallback(pr.changeTime1);
changerTimer1 = new Timer(changeTimedel1, null, 0, 10);
Console.ReadLine();
}
}
}
答案 0 :(得分:0)
尝试计算到期时间:
class Program
{
static DateTime _lastInvokation;
static int somedelInterval = 10000;
public void someFun1(Object obj)
{
Console.WriteLine("Start1 " + DateTime.Now);
_lastInvokation = DateTime.Now;
}
public void changeTime1(Object obj)
{
int dueTime = somedelInterval - (int)(DateTime.Now - _lastInvokation).TotalMilliseconds;
somedelInterval = 2000;
if (dueTime > 0)
someTime1.Change(dueTime, somedelInterval);
}
public static TimerCallback somedel1;
public static Timer someTime1;
public static TimerCallback changeTimedel1;
public static Timer changerTimer1;
static void Main(string[] args)
{
Program pr = new Program();
somedel1 = new TimerCallback(pr.someFun1);
someTime1 = new Timer(somedel1, null, Timeout.Infinite, somedelInterval);
_lastInvokation = DateTime.Now;
changeTimedel1 = new TimerCallback(pr.changeTime1);
changerTimer1 = new Timer(changeTimedel1, null, 0, 10);
Console.ReadLine();
}
}