簡體   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