動くコード図鑑技術記事現場の渡り方キャリア論すべての記事About
C#

System.Threading.Timer —スレッドプール発火の軽量版

出典: WinForms Timer 3兄弟の使い分け — System.Windows.Forms.Timer / System.Threading.Timer / System.Timers.TimerSystem.Threading.Timer —スレッドプール発火の軽量版

System.Threading.Timer —スレッドプール発火の軽量版 (csharp)#db033bd6db6b
// ✅パターン2: System.Threading.Timer(バックグラウンド計算)
using System.Threading;
 
public partial class LogMonitorForm : Form
{
    private System.Threading.Timer _bgTimer;
    private int _processedCount = 0;
 
    public LogMonitorForm()
    {
        InitializeComponent();
 
        // dueTime=0(即座に開始)/ period=5000(5秒ごと)
        _bgTimer = new System.Threading.Timer(BackgroundCheck, null, 0, 5000);
    }
 
    private void BackgroundCheck(object state)
    {
        //ここはスレッドプール上で動く→ UIコントロールを直接触ると例外
        var newLogs = LogReader.PollNewEntries();
        _processedCount += newLogs.Count;
 
        // UI更新はControl.InvokeでUIスレッドにマーシャリング(次のセクション参照)
        if (this.IsHandleCreated && !this.IsDisposed)
        {
            this.BeginInvoke(new Action(()=>
            {
                labelStatus.Text = $"処理済: {_processedCount}件";
            }));
        }
    }
 
    private void LogMonitorForm_FormClosing(object sender, FormClosingEventArgs e)
    {
        _bgTimer?.Dispose();   // Threading.TimerはStopメソッドがない、Disposeで停止
    }
}
▸ この snippet は実行結果未収録
▸ 実行結果は未収録です
  • id: #db033bd6db6b
  • lines: 37
  • extracted: 2026-06-10

Source収録記事

この snippet は記事の「System.Threading.Timer —スレッドプール発火の軽量版」セクションに登場する。コードの前後の文脈・ハマりどころの解説は記事本文で。

同じ記事から

4
図鑑トップ