2014-03-25 39 views
0

我有一个问题。我创建了两个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

试算duetime参数:

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(); 
     } 
    } 
+0

,但它不工作( – user3458708

+0

好吧,你需要保存定时器的当前状态,我已经编辑我的帖子 – Alex