3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

C#でTimerのコールバック処理を順次処理にしたい

Posted at

1. はじめに

  • C#のTimerのコールバック処理に時間がかかる時に処理が並行しないようにしたい

2. 開発環境

  • C#
  • .NET 6
  • Visual Studio 2022

3. 変更前のソース

public class Sample : IExecutable
{
  public void Execute()
  {
    var timer = new System.Threading.Timer(TimerCallback);
    timer.Change(0, 1000);
    
    Thread.Sleep(10000);
  }
    
  void TimerCallback(object state)
  {
    // 時間がかかるコールバック処理
    Thread.Sleep(9000);
  }
}

4. 変更後のソース

public class Sample : IExecutable
{
  public void Execute()
  {
    var timer = new System.Threading.Timer(TimerCallback);

    // 呼び出し間隔をセットしない
    timer.Change(0, Timeout.Infinite);
    
    Thread.Sleep(10000);
  }
    
  void TimerCallback(object state)
  {
    // 時間がかかるコールバック処理
    Thread.Sleep(9000);

    // コールバック処理後に再度呼び出し間隔をセットする
    var timer = state as System.Threading.Timer;
    timer.Change(1000, Timeout.Infinite);
  }
}

5. 参考文献

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?