簡體   English   中英

1 System.Timers.Timer = 1個線程?

[英]1 System.Timers.Timer = 1 thread?

每個計時器是否有1個線程?

例如 :

class MyObj
{
    private Timer _timer;

    public MyObj()
    {
        Initialize();
    }

    private void Initialize()
    {
        _timer = new Timer(2000);
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        _timer.Start();
    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("MyObj !");
    }


}
class Program
{
    private static Timer _timer;

    private static void Main(string[] args)
    {
        _timer = new Timer(500);
        _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        _timer.Start();
        MyObj mo = new MyObj();
        Console.Read();
    }

    static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        Console.WriteLine("Program !");
    }
}

有2個線程嗎?

計時器使用ThreadPool因此最多只能使用2個線程。 但是,由於ThreadPool中的ThreadPool被回收,它可能最終使用同一線程兩次,或者使用兩個線程,但不能同時使用。

計時器本身不會導致線程的創建。

另外,如果您的計時器永遠不會計時-它不會將任何工作發布到ThreadPool因此從本質上講不會“花費”您任何線程。

要知道,雖然蜱線程是不確定的......你上創建計時器線程不是線程刻度將在發生。 滴答聲中的任何邏輯都需要意識到它可能與類中的其他內容並行運行。

不,每個計時器都沒有保留線程。 該事件在線程池線程上進行調度,並且在事件處理程序未運行時計時器不會阻塞線程。 由於存在多個線程池線程,因此事件處理程序仍然需要是線程安全的。

文件說明:

如果SynchronizingObject屬性為Nothing ,則在ThreadPool線程上引發Elapsed事件。 如果對Elapsed事件的處理持續時間長於Interval ,則該事件可能在另一個ThreadPool線程上再次引發。 在這種情況下,事件處理程序應該是可重入的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM