【问题标题】:How to change timed thread interval from another timer?如何从另一个计时器更改定时线程间隔?
【发布时间】:2014-03-25 09:38:43
【问题描述】:

我有问题。我创建了两个 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();
        }
    }
}

【问题讨论】:

    标签: c# multithreading timer


    【解决方案1】:

    尝试计算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();
            }
        }
    

    【讨论】:

    • 好的,你需要保存定时器的当前状态吗?我已经编辑了我的帖子
    猜你喜欢
    • 2013-08-09
    • 1970-01-01
    • 2023-04-02
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    相关资源
    最近更新 更多