1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】【WPF】DipatcherTimerとTimerの使い分け

Last updated at Posted at 2024-11-29

一定間隔で処理を行う場面ではTimerに処理を移譲することを考えることがあると思います。

ここで2つのTimerが見つかりました。

DispatcherTimerはUIをブロックする。
(名前空間System.Windows.Threading;)

TimerはUIをブロックしない。
(名前空間System.Timers;)

メッセージボックスを出してみる処理を作るとわかりやすいと思いました。

DisptcherTimertはUIスレッドで同期的に処理をするがTimerは別スレッドで非同期的に処理を行っていると言えると思います。

1.DispatcherTimerを使う

using System;
using System.Windows;
using System.Windows.Threading;

namespace TimerSample
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        DispatcherTimer MyDispatcherTimer;

        public MainWindow()
        {
            InitializeComponent();

            MyDispatcherTimer = new DispatcherTimer();
            MyDispatcherTimer.Tick += Timer_Tick;
            MyDispatcherTimer.Interval = TimeSpan.FromSeconds(1);
            MyDispatcherTimer.Start();

        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            MessageBox.Show(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
        }
    }
}


2.Timerを使う

using System;
using System.Timers;
using System.Windows;

namespace UIをブロックしないTimer
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        Timer MyTimer;

        public MainWindow()
        {
            InitializeComponent();

            MyTimer = new Timer();
            MyTimer.Elapsed += MyTimer_Elapsed;
            MyTimer.Interval = 1000;
            MyTimer.Start();

        }

        private void MyTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            MessageBox.Show(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
        }
    }
}
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?