繁体   English   中英

C# 有没有办法在触发计时器时“重新启动”线程?

[英]C# Is there a way to "restart" a thread when a timer is triggered?

我想制作一个包含 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();
    }
} 

答案是不...

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

但是,如果您确实必须使用Thread ,则可以再次创建它然后Start

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

这是一个有点“通用”的答案,但我能想到的唯一解决方案是在您的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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM