以不同的时间间隔同时执行两种不同的方法c#

问题描述 投票:0回答:2

我正在尝试实现两种不同的方法,以不同的时间间隔同时开始执行。 method1()每5分钟执行一次,method2()每10分钟执行一次。我正在使用控制台应用程序来实现这一目标。

    public static Int64 counter = 0;
    static void Main(string[] args)
    {            
        bool tryAgain = true;
        while (tryAgain)
        {
            try
            {
                Thread thread1 = new Thread(new ThreadStart(TimerMethod1));
                Thread thread2 = new Thread(new ThreadStart(TimerMethod2));

                thread1.Start();
                thread2.Start();
            }
            catch(Exception ex)                
            {
                Thread thread1 = new Thread(new ThreadStart(TimerMethod1));
                Thread thread2 = new Thread(new ThreadStart(TimerMethod2));

                thread1.Start();
                thread2.Start();

                Console.WriteLine("Error ==>" + ex.ToString());
            }
        }
    }     
    public static void method1(object sender, System.Timers.ElapsedEventArgs e)
    {           
        Console.WriteLine("method1 --" + System.DateTime.Now.ToString() + "=====>" + counter.ToString());
        counter++;
    }
    public static void method2(object sender, ElapsedEventArgs e)
    {            
        Console.WriteLine("method2 --" + System.DateTime.Now.ToString());           
    }

    public static void TimerMethod1()
    {
        System.Timers.Timer t = new System.Timers.Timer(TimeSpan.FromMinutes(5).TotalMilliseconds); //execute every 5 minutes
        t.AutoReset = true;
        t.Elapsed += new System.Timers.ElapsedEventHandler(method1);
        t.Start();
    }
    public static void TimerMethod2()
    {
        System.Timers.Timer t = new System.Timers.Timer(TimeSpan.FromMinutes(10).TotalMilliseconds); //execute every 10 minutes
        t.AutoReset = true;
        t.Elapsed += new System.Timers.ElapsedEventHandler(method2);
        t.Start();
    } 

我正在使用两个不同的计时器来管理每种方法。这使执行进入循环而无需遵循计时器。 counter仅用于检查特定方法的出现次数。

注意:我只想同时开始执行这两种方法。两者都应该独立工作,一旦启动就不要互相依赖。

c# multithreading console-application
2个回答
0
投票

除非我误解了对专用线程的要求,否则可以使用Task进行此操作以允许异步操作。单个计时器可以与分配的Elapsed事件分配任务一起使用,以运行您的方法。可以“切换”一个简单的bool来确定每五分钟的迭代是否调用Method2()。

class Program
{
    static bool runMethod2;

    static void Main(string[] args)
    {
        runMethod2 = true;
        Timer masterTimer = new Timer()
        {
            // Interval of 5 minutes in ms
            Interval = 5 * 60 * 1000
        };
        masterTimer.Elapsed += EventManager;
        masterTimer.Start();

        while (true) { }

    }

    private static void EventManager(object sender, ElapsedEventArgs e)
    {
        runMethod2 = !runMethod2;
        Task.Run(() => Method1());
        if (runMethod2) Task.Run(() => Method2());
    }

    static void Method1()
    {

    }

    static void Method2()
    {

    }
}

0
投票

您可以大大简化代码并直接使用计时器

Timer t1 = new Timer(TimeSpan.FromMinutes(5).TotalMilliseconds)
{
    AutoReset = true
}; //execute every 5 minutes
t1.Elapsed += method1;

Timer t2 = new Timer(TimeSpan.FromMinutes(10).TotalMilliseconds)
{
    AutoReset = true
}; //execute every 10 minutes
t2.Elapsed += method2;

bool tryAgain = true;
while (tryAgain)
{
    try
    {
        t1.Start();
        t2.Start();
    }
    catch (Exception ex)
    {
        t1.Start();
        t2.Start();
        Console.WriteLine("Error ==>" + ex);
    }
}

Elapsed事件在Elapsed线程上被调用,无需创建单独的线程来运行计时器。

具有ThreadPool循环并重试逻辑在这里也显得毫无意义,当while无效时,Start方法只能抛出ArgumentOutOfRangeException。您可以用[]完全替换Interval循环

while
© www.soinside.com 2019 - 2024. All rights reserved.