User Tools

Site Tools


blog:2025-05-06-001



2025-05-06 C# winform 以 Systerm.Timer 所產生的 Timer 如何於程式退出時一併關閉

  • 在 C# WinForms 中,如果使用 System.Timers.Timer,您需要確保在應用程式退出時正確關閉計時器
  • 這樣可以避免在應用程式結束時仍有活動的計時器導致潛在的問題
  • 以下是如何在程式退出時關閉 System.Timers.Timer 的範例:

1. 使用 Form.FormClosing 事件

  • 可以在表單的 FormClosing 事件中停止計時器
  • 以下是範例代碼:
  • using System;
    using System.Timers;
    using System.Windows.Forms;
    
    namespace TimerExample
    {
        public partial class MainForm : Form
        {
            private Timer _timer;
    
            public MainForm()
            {
                InitializeComponent();
                InitializeTimer();
            }
    
            private void InitializeTimer()
            {
                _timer = new Timer(1000); // 每秒觸發一次
                _timer.Elapsed += OnTimedEvent;
                _timer.AutoReset = true;
                _timer.Enabled = true;
            }
    
            private void OnTimedEvent(object source, ElapsedEventArgs e)
            {
                // 計時器事件處理邏輯
                Console.WriteLine("Timer triggered at: " + e.SignalTime);
            }
    
            protected override void OnFormClosing(FormClosingEventArgs e)
            {
                // 停止計時器
                if (_timer != null)
                {
                    _timer.Stop();
                    _timer.Dispose(); // 釋放資源
                }
                base.OnFormClosing(e);
            }
        }
    }

2. 重要步驟說明

  • 初始化計時器:在 MainForm 的構造函數中初始化計時器
  • 事件處理:定義計時器的事件處理函數 OnTimedEvent
  • 關閉計時器:在 OnFormClosing 方法中,停止並釋放計時器資源
  • 這樣,當關閉應用程式時,計時器將會被正確地停止和釋放,避免任何潛在的問題 *

TAGS

  • 37 person(s) visited this page until now.

blog/2025-05-06-001.txt · Last modified: 2025/05/06 09:31 by jethro