【问题标题】:C# Is there a way to "restart" a thread when a timer is triggered?C# 有没有办法在触发计时器时“重新启动”线程?
【发布时间】:2020-06-05 08:13:17
【问题描述】:

我想制作一个包含 2 个线程的程序,每次触发计时器时都会重复调用这些线程。

我知道您在技术上无法重新启动线程,但我想知道是否有任何解决方法可以解决此问题?

using System; 
using System.Threading; 

public class Program { 

    // static method one 
    static void method1() 
    { 
        // some code here
    } 

    // static method two 
    static void method2() 
    { 
        // some code here
    } 

    // Main Method 
    public void Main() 
    { 
        // Creating and initializing timer
        System.Timers.Timer MyTimer = new System.Timers.Timer();
        MyTimer.Interval = 4000;
        MyTimer.Tick += new EventHandler(timer1_Tick);
        MyTimer.Start();
        autoResetEvent = new AutoResetEvent(false);

        // Creating and initializing threads 
        Thread thr1 = new Thread(method1); 
        Thread thr2 = new Thread(method2);

        thr1.Start(); 
        thr2.Start(); 
    } 

    private void timer1_Tick(object sender, EventArgs e)
    {
        // code below is wrong. I want to repeat/restart the threads
        thr1.Start(); 
        thr2.Start();
    }
} 

【问题讨论】:

  • 线程就像生物一样。一旦他们结束,他们就结束了。如果你想重用它们,你必须专门让它们保持活力。您是否特别需要使用相同的线程?
  • 如果在第二个Tick 事件发生时,一个或两个线程仍在从第一个Tick 事件运行,您希望发生什么?
  • 视情况而定。你希望你的任务重复吗?或者你假设你的任务被打断了?如果Task 不适合您的用例,您可以编辑您的帖子。

标签: c# multithreading timer


【解决方案1】:

答案是否定的……

此外,我会认真考虑使用任务而不是 Thread 类。

但是,如果你真的必须使用Thread,你可以再次创建它然后Start

选项 2(并且可能不太容易出现问题),在您的 thread 中放置一个 loop 并使用类似 AutoResetEvent 的东西来触发它应该继续循环

【讨论】:

    【解决方案2】:

    这是一个“通用”的答案,但我能想到的唯一解决方案是在您的 timer1_Tick 函数中,销毁/停止旧线程并创建新线程,看起来像这样:

    // make sure the threads are stopped.
    thr1.Stop();
    thr2.Stop();
    
    // make and start new threads.
    thr1 = new Thread(method1); 
    thr2 = new Thread(method2);
    thr1.Start();
    thr2.Start();
    

    【讨论】:

    • 虽然这是一个合法的答案,但值得未来读者注意,永远不要中止 线程,它很危险,是糟糕设计的症状,并且只能在紧急情况下使用
    • Thread 类不包含 Stop 方法。
    猜你喜欢
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    相关资源
    最近更新 更多