<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lee, Cheul Woo on Medium]]></title>
        <description><![CDATA[Stories by Lee, Cheul Woo on Medium]]></description>
        <link>https://medium.com/@leechw9_78853?source=rss-6f665fbb3583------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by Lee, Cheul Woo on Medium</title>
            <link>https://medium.com/@leechw9_78853?source=rss-6f665fbb3583------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 01:50:48 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@leechw9_78853/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[C# Task.GetAwaiter and GetResult with Appication.OnExit(Window.Closing)]]></title>
            <link>https://medium.com/@leechw9_78853/c-task-getawaiter-and-getresult-with-appication-onexit-window-closing-319bb635a3f1?source=rss-6f665fbb3583------2</link>
            <guid isPermaLink="false">https://medium.com/p/319bb635a3f1</guid>
            <category><![CDATA[wpf]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[asynchronous-programming]]></category>
            <dc:creator><![CDATA[Lee, Cheul Woo]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 00:03:23 GMT</pubDate>
            <atom:updated>2025-12-24T00:03:23.063Z</atom:updated>
            <content:encoded><![CDATA[<p>Lee, Cheul Woo</p><p>If you want to terminate with some System.Threading.Tasks.Task when your C# WPF app exits, you should use Task.GetAwaiter() and GetResult() instead of async/await. The appropriate termination event is Application.OnExit (or Window.Closing).</p><p>Create a .Net 9 WPF app project using Visual Studio 2022 Community.</p><p>Remove StartupUri=”MainWindow.xaml” from the App.xaml file.</p><blockquote>&lt;Application x:Class=”Study.Wpf.TestGetAwaiter.App”<br> xmlns=”<a href="http://schemas.microsoft.com/winfx/2006/xaml/presentation">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a>&quot;<br> xmlns:x=”<a href="http://schemas.microsoft.com/winfx/2006/xaml">http://schemas.microsoft.com/winfx/2006/xaml</a>&quot;<br> xmlns:local=”clr-namespace:Study.Wpf.TestGetAwaiter”&gt;<br> &lt;Application.Resources&gt;<br> &lt;/Application.Resources&gt;<br>&lt;/Application&gt;</blockquote><p>In App.xaml.cs, change the class App as shown below. Here, Task.Delay takes care of the terminiating(finishing) task.</p><blockquote>public partial class App : Application<br> {<br> protected override void OnStartup(StartupEventArgs e)<br> {<br> base.OnStartup(e);<br> AllocConsole();<br> Console.WriteLine(nameof(OnStartup));</blockquote><blockquote>MainWindow = new MainWindow();<br> MainWindow.Show();<br> }</blockquote><blockquote>protected override void OnExit(ExitEventArgs e)<br> {<br> Task.Delay(3000).GetAwaiter().GetResult();<br> Console.WriteLine(nameof(Task.Delay));<br> Console.ReadLine();</blockquote><blockquote>Console.WriteLine(nameof(OnExit));<br> FreeConsole();<br> base.OnExit(e);<br> }</blockquote><blockquote>[DllImport(“kernel32.dll”, SetLastError = true)]<br> public static extern bool AllocConsole();</blockquote><blockquote>[DllImport(“kernel32.dll”, SetLastError = true)]<br> public static extern bool FreeConsole();<br> }</blockquote><p>If you build this, run it, and exit, you’ll see that it outputs ‘Delay’(terminating) after 3 seconds.</p><blockquote>protected override async void OnExit(ExitEventArgs e)<br> {<br> //Task.Delay(3000).GetAwaiter().GetResult();<br> await Task.Delay(3000).ConfigureAwait(false);<br> Console.WriteLine(nameof(Task.Delay));<br> Console.ReadLine();</blockquote><blockquote>Console.WriteLine(nameof(OnExit));<br> FreeConsole();<br> base.OnExit(e);<br> }</blockquote><p>Task.GetAwaiter() and GetResult(), which are usually avoided in asynchronous programs, play an important role in the above situation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=319bb635a3f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# SynchronizationContext Usage]]></title>
            <link>https://medium.com/@leechw9_78853/c-synchronizationcontext-usage-26893a2e61f6?source=rss-6f665fbb3583------2</link>
            <guid isPermaLink="false">https://medium.com/p/26893a2e61f6</guid>
            <category><![CDATA[dispatcher]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[wpf]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Lee, Cheul Woo]]></dc:creator>
            <pubDate>Mon, 06 Oct 2025 11:38:36 GMT</pubDate>
            <atom:updated>2025-10-06T11:52:11.181Z</atom:updated>
            <content:encoded><![CDATA[<p>Timers are a key element in determining the observation cycle in programs requiring periodic monitoring. Unlike Windows services, monitoring programs typically have a screen (GUI). This article will explain why SynchronizationContext is necessary while implementing and advancing an app with a timer and a screen using C# WPF technology (.NET 9).</p><p>The app we’ll be building in this article has the following features: If you set a random period (Period) for a timer, a timer event will occur at that period, and each time an event occurs, the time it occurs (displayed to 0.1 second units) and the number of times the event occurs (Count) will be displayed on the screen. Additionally, the quotient (Ellapsed) is calculated by dividing the difference between the set period time and the time the timer event occurs by the period and displaying it on the screen. If the two values ​​(Count, Ellapsed) differ, the reset button will be enabled; if they are the same, the reset button will be disabled. Assuming that a timer event hasn’t occurred at the specified period, the number of occurrences (Count) will be less than the quotient (Ellapsed). Pressing the reset button will reset the number of occurrences (Count) and the quotient (Ellapsed) to 0, restarting the timer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*YuyyfMqxBU-vZdCoB10-_A.png" /></figure><p>The development tool is Microsoft Visual Studio Community 2022 (64-bit) Version 17.14.16.</p><p><strong>Using DispatcherTimer and the Visual Studio Template Pattern</strong></p><p>Create a WPF project using the development tool. This project is called [Visual Studio Template Pattern].<br>Modify MainWindow.xaml and MainWindow.xaml.cs as shown below.</p><pre>&lt;Window x:Class=&quot;Clock.UiTimer.VstPattern.MainWindow&quot;<br>        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;<br>        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;<br>        xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;<br>        xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;<br>        xmlns:local=&quot;clr-namespace:Clock.UiTimer.VstPattern&quot;<br>        mc:Ignorable=&quot;d&quot;<br>        Title=&quot;MainWindow&quot; Height=&quot;160&quot; Width=&quot;480&quot; FontSize=&quot;14&quot;&gt;<br>    &lt;Grid&gt;<br>        &lt;DockPanel HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Bottom&quot; Background=&quot;{x:Static SystemColors.ControlBrush}&quot;&gt;<br>            &lt;Label DockPanel.Dock=&quot;Left&quot;/&gt;<br>            &lt;TextBlock x:Name=&quot;TextBlockMessage&quot; DockPanel.Dock=&quot;Left&quot;/&gt;<br>        &lt;/DockPanel&gt;<br>        &lt;Grid&gt;<br>            &lt;Grid.ColumnDefinitions&gt;<br>                &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;2*&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;*&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;*&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;<br>            &lt;/Grid.ColumnDefinitions&gt;<br>            &lt;Grid.RowDefinitions&gt;<br>                &lt;RowDefinition Height=&quot;Auto&quot;/&gt;<br>                &lt;RowDefinition Height=&quot;*&quot;/&gt;<br>            &lt;/Grid.RowDefinitions&gt;<br>            &lt;Label Grid.Column=&quot;0&quot; Grid.RowSpan=&quot;2&quot;/&gt;<br>            &lt;Label Grid.Column=&quot;4&quot; Grid.RowSpan=&quot;2&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;1&quot; Grid.Row=&quot;0&quot; Text=&quot;&quot; TextAlignment=&quot;Center&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;2&quot; Grid.Row=&quot;0&quot; Text=&quot;Ellapsed&quot; TextAlignment=&quot;Center&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;3&quot; Grid.Row=&quot;0&quot; Text=&quot;Count&quot; TextAlignment=&quot;Center&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot; x:Name=&quot;TextBlockTime&quot; TextAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; FontSize=&quot;48&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;2&quot; Grid.Row=&quot;1&quot; x:Name=&quot;TextBlockEllapsedTime&quot; TextAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; FontSize=&quot;48&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;3&quot; Grid.Row=&quot;1&quot; x:Name=&quot;TextBlockCount&quot; TextAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; FontSize=&quot;48&quot;/&gt;<br>        &lt;/Grid&gt;<br>        &lt;DockPanel LastChildFill=&quot;False&quot; HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Top&quot;&gt;<br>            &lt;Label DockPanel.Dock=&quot;Left&quot;/&gt;<br>            &lt;Button x:Name=&quot;ButtonReset&quot; Content=&quot;Reset&quot; HorizontalAlignment=&quot;Left&quot; VerticalAlignment=&quot;Top&quot;/&gt;<br>            &lt;TextBox x:Name=&quot;TextBoxPeriod&quot; TextAlignment=&quot;Right&quot;/&gt;<br>            &lt;TextBlock Text=&quot;msec&quot; TextAlignment=&quot;Left&quot;/&gt;<br>        &lt;/DockPanel&gt;<br>    &lt;/Grid&gt;<br>&lt;/Window&gt;</pre><pre>using System.Windows;<br>using System.Windows.Threading;<br><br>namespace Clock.UiTimer.VstPattern<br>{<br>    /// &lt;summary&gt;<br>    /// Interaction logic for MainWindow.xaml<br>    /// &lt;/summary&gt;<br>    public partial class MainWindow : Window<br>    {<br>        private readonly DispatcherTimer _dispatcherTimer;<br>        private DateTimeOffset _resetTime;<br>        private int _period;<br><br>        public MainWindow()<br>        {<br>            InitializeComponent();<br>            Title = TITLE;<br><br>            ButtonReset.IsEnabled = false;<br>            ButtonReset.Click += ButtonReset_Click;<br>            TextBoxPeriod.TextChanged += TextBoxPeriod_TextChanged;<br><br>            Loaded += MainWindow_Loaded;<br>            Closing += MainWindow_Closing;<br><br>            _dispatcherTimer = new DispatcherTimer();<br>            _dispatcherTimer.Tick += DispatcherTimer_Tick;<br><br>            TextBoxPeriod.Text = DEFAULT_PERIOD;<br>        }<br><br>        private void TextBoxPeriod_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)<br>        {<br>            try<br>            {<br>                var period = Convert.ToInt32(TextBoxPeriod.Text);<br>                if (period &gt; 0)<br>                {<br>                    _period = period;<br>                    Reset();<br>                }<br>            }<br>            catch (FormatException)<br>            {<br>            }<br>        }<br><br>        private void ButtonReset_Click(object sender, RoutedEventArgs e)<br>        {<br>            Reset();<br>        }<br><br>        private void MainWindow_Loaded(object sender, RoutedEventArgs e)<br>        {<br>            Loaded -= MainWindow_Loaded;<br>            Reset();<br>        }<br><br>        private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)<br>        {<br>            Closing -= MainWindow_Closing;<br>            _dispatcherTimer.Stop();<br><br>            TextBoxPeriod.TextChanged -= TextBoxPeriod_TextChanged;<br>            ButtonReset.Click -= ButtonReset_Click;<br>            _dispatcherTimer.Tick -= DispatcherTimer_Tick;<br>        }<br><br>        private void DispatcherTimer_Tick(object? sender, EventArgs e)<br>        {<br>            Time = DateTimeOffset.Now;<br>            Count++;<br>            Ellapsed = (Time.ToUnixTimeMilliseconds() - _resetTime.ToUnixTimeMilliseconds()) / _period;<br><br>            var notEqual = (Count != Ellapsed);<br>            ButtonReset.IsEnabled = notEqual;<br>            if (string.IsNullOrEmpty(TextBlockMessage.Text))<br>            {<br>                if (notEqual)<br>                {<br>                    TextBlockMessage.Text = string.Format(COUNT_IS_NOT_EQUAL_ELLAPSED, Count, Ellapsed, Time.ToString(TIME_FORMAT));<br>                }<br>            }<br>            else<br>            {<br>                if (!notEqual)<br>                {<br>                    TextBlockMessage.Text = string.Empty;<br>                }<br>            }<br>        }<br><br>        public DateTimeOffset Time<br>        {<br>            get =&gt; _time;<br>            set<br>            {<br>                if (value != _time)<br>                {<br>                    _time = value;<br>                    TextBlockTime.Text = value.ToString(TIME_FORMAT);<br>                }<br>            }<br>        }<br>        private DateTimeOffset _time;<br><br>        public long Count<br>        {<br>            get =&gt; _count;<br>            set<br>            {<br>                if (_count != value)<br>                {<br>                    _count = value;<br>                    TextBlockCount.Text = value.ToString();<br>                }<br>            }<br>        }<br>        private long _count = -1;<br><br>        public long Ellapsed<br>        {<br>            get =&gt; _ellapsedSeconds;<br>            set<br>            {<br>                if (_ellapsedSeconds != value)<br>                {<br>                    _ellapsedSeconds = value;<br>                    TextBlockEllapsedTime.Text = value.ToString();<br>                }<br>            }<br>        }<br>        private long _ellapsedSeconds = -1;<br><br>        private void Reset()<br>        {<br>            _dispatcherTimer.Stop();<br>            ButtonReset.IsEnabled = false;<br>            TextBlockMessage.Text = string.Empty;<br><br>            Count = 0;<br>            Ellapsed = 0;<br><br>            Time = DateTimeOffset.Now;<br>            _resetTime = Time;<br><br>            _dispatcherTimer.Interval = TimeSpan.FromMilliseconds(_period);<br>            _dispatcherTimer.Start();<br>        }<br><br>        private readonly static string TITLE = &quot;Clock - DispatcherTimer - VisualStudio Template Pattern&quot;;<br>        private readonly static string DEFAULT_PERIOD = &quot;1000&quot;;<br>        private readonly static string TIME_FORMAT = &quot;HH:mm:ss.f&quot;;<br>        private readonly static string COUNT_IS_NOT_EQUAL_ELLAPSED = &quot;Count({0}) is not equal to ellapsed({1}) at {2}.&quot;;<br>    }<br>}</pre><p>To reuse the UI in future projects, all UI events were added/removed from MainWindow.xaml.cs.<br>[Start without debugging]. Change the period between 1000 msec and 1 msec. You’ll notice that the reset button activates more quickly as the period decreases. Because DispatcherTimer runs on the UI thread, the number of occurrences (Count) is less than the quotient (Ellapsed). This decrease in timer events can be a bug in some programs.</p><p><strong>Using Threading.Timer and the Visual Studio Template Pattern</strong></p><p>Create a WPF project using the development tool. Modify MainWindow.xaml and MainWindow.xaml.cs as shown below. The contents of MainWindow.xaml were copied from the project.</p><pre>&lt;Window x:Class=&quot;Clock.ThreadTimer.VstPattern.MainWindow&quot;<br>        xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;<br>        xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;<br>        xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot;<br>        xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot;<br>        xmlns:local=&quot;clr-namespace:Clock.ThreadTimer.VstPattern&quot;<br>        mc:Ignorable=&quot;d&quot;<br>        Title=&quot;MainWindow&quot; Height=&quot;160&quot; Width=&quot;480&quot; FontSize=&quot;14&quot;&gt;<br>    &lt;Grid&gt;<br>        &lt;DockPanel HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Bottom&quot; Background=&quot;{x:Static SystemColors.ControlBrush}&quot;&gt;<br>            &lt;Label DockPanel.Dock=&quot;Left&quot;/&gt;<br>            &lt;TextBlock x:Name=&quot;TextBlockMessage&quot; DockPanel.Dock=&quot;Left&quot;/&gt;<br>        &lt;/DockPanel&gt;<br>        &lt;Grid&gt;<br>            &lt;Grid.ColumnDefinitions&gt;<br>                &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;2*&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;*&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;*&quot;/&gt;<br>                &lt;ColumnDefinition Width=&quot;Auto&quot;/&gt;<br>            &lt;/Grid.ColumnDefinitions&gt;<br>            &lt;Grid.RowDefinitions&gt;<br>                &lt;RowDefinition Height=&quot;Auto&quot;/&gt;<br>                &lt;RowDefinition Height=&quot;*&quot;/&gt;<br>            &lt;/Grid.RowDefinitions&gt;<br>            &lt;Label Grid.Column=&quot;0&quot; Grid.RowSpan=&quot;2&quot;/&gt;<br>            &lt;Label Grid.Column=&quot;4&quot; Grid.RowSpan=&quot;2&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;1&quot; Grid.Row=&quot;0&quot; Text=&quot;&quot; TextAlignment=&quot;Center&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;2&quot; Grid.Row=&quot;0&quot; Text=&quot;Ellapsed&quot; TextAlignment=&quot;Center&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;3&quot; Grid.Row=&quot;0&quot; Text=&quot;Count&quot; TextAlignment=&quot;Center&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot; x:Name=&quot;TextBlockTime&quot; TextAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; FontSize=&quot;48&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;2&quot; Grid.Row=&quot;1&quot; x:Name=&quot;TextBlockEllapsedTime&quot; TextAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; FontSize=&quot;48&quot;/&gt;<br>            &lt;TextBlock Grid.Column=&quot;3&quot; Grid.Row=&quot;1&quot; x:Name=&quot;TextBlockCount&quot; TextAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; FontSize=&quot;48&quot;/&gt;<br>        &lt;/Grid&gt;<br>        &lt;DockPanel LastChildFill=&quot;False&quot; HorizontalAlignment=&quot;Stretch&quot; VerticalAlignment=&quot;Top&quot;&gt;<br>            &lt;Label DockPanel.Dock=&quot;Left&quot;/&gt;<br>            &lt;Button x:Name=&quot;ButtonReset&quot; Content=&quot;Reset&quot; HorizontalAlignment=&quot;Left&quot; VerticalAlignment=&quot;Top&quot;/&gt;<br>            &lt;TextBox x:Name=&quot;TextBoxPeriod&quot; TextAlignment=&quot;Right&quot;/&gt;<br>            &lt;TextBlock Text=&quot;msec&quot; TextAlignment=&quot;Left&quot;/&gt;<br>        &lt;/DockPanel&gt;<br>    &lt;/Grid&gt;<br>&lt;/Window&gt;</pre><pre>using System.Windows;<br>using System.Windows.Threading;<br><br>namespace Clock.ThreadTimer.VstPattern<br>{<br>    /// &lt;summary&gt;<br>    /// Interaction logic for MainWindow.xaml<br>    /// &lt;/summary&gt;<br>    public partial class MainWindow : Window<br>    {<br>        private readonly Timer _threadingTimer;<br>        private DateTimeOffset _resetTime;<br>        private int _period;<br><br>        public MainWindow()<br>        {<br>            InitializeComponent();<br>            Title = TITLE;<br><br>            ButtonReset.IsEnabled = false;<br>            ButtonReset.Click += ButtonReset_Click;<br>            TextBoxPeriod.TextChanged += TextBoxPeriod_TextChanged;<br><br>            Loaded += MainWindow_Loaded;<br>            Closing += MainWindow_Closing;<br><br>            _threadingTimer = new Timer(Callback, null, Timeout.Infinite, Timeout.Infinite);<br><br>            TextBoxPeriod.Text = DEFAULT_PERIOD;<br>        }<br><br>        private void TextBoxPeriod_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)<br>        {<br>            try<br>            {<br>                var period = Convert.ToInt32(TextBoxPeriod.Text);<br>                if (period &gt; 0)<br>                {<br>                    _period = period;<br>                    Reset();<br>                }<br>            }<br>            catch (FormatException)<br>            {<br>            }<br>        }<br><br>        private void ButtonReset_Click(object sender, RoutedEventArgs e)<br>        {<br>            Reset();<br>        }<br><br>        private void MainWindow_Loaded(object sender, RoutedEventArgs e)<br>        {<br>            Loaded -= MainWindow_Loaded;<br>            Reset();<br>        }<br><br>        private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)<br>        {<br>            Closing -= MainWindow_Closing;<br>            _threadingTimer.Dispose();<br><br>            TextBoxPeriod.TextChanged -= TextBoxPeriod_TextChanged;<br>            ButtonReset.Click -= ButtonReset_Click;<br>        }<br><br>        private void Callback(object? state)<br>        {<br>            Dispatcher.BeginInvoke(() =&gt;<br>            {<br>                Time = DateTimeOffset.Now;<br>                Count++;<br>                Ellapsed = (Time.ToUnixTimeMilliseconds() - _resetTime.ToUnixTimeMilliseconds()) / _period;<br><br>                var notEqual = (Count != Ellapsed);<br>                ButtonReset.IsEnabled = notEqual;<br>                if (string.IsNullOrEmpty(TextBlockMessage.Text))<br>                {<br>                    if (notEqual)<br>                    {<br>                        TextBlockMessage.Text = string.Format(COUNT_IS_NOT_EQUAL_ELLAPSED, Count, Ellapsed, Time.ToString(TIME_FORMAT));<br>                    }<br>                }<br>                else<br>                {<br>                    if (!notEqual)<br>                    {<br>                        TextBlockMessage.Text = string.Empty;<br>                    }<br>                }<br>            });<br>        }<br><br>        public DateTimeOffset Time<br>        {<br>            get =&gt; _time;<br>            set<br>            {<br>                if (value != _time)<br>                {<br>                    _time = value;<br>                    TextBlockTime.Text = value.ToString(TIME_FORMAT);<br>                }<br>            }<br>        }<br>        private DateTimeOffset _time;<br><br>        public long Count<br>        {<br>            get =&gt; _count;<br>            set<br>            {<br>                if (_count != value)<br>                {<br>                    _count = value;<br>                    TextBlockCount.Text = value.ToString();<br>                }<br>            }<br>        }<br>        private long _count = -1;<br><br>        public long Ellapsed<br>        {<br>            get =&gt; _ellapsed;<br>            set<br>            {<br>                if (_ellapsed != value)<br>                {<br>                    _ellapsed = value;<br>                    TextBlockEllapsedTime.Text = value.ToString();<br>                }<br>            }<br>        }<br>        private long _ellapsed = -1;<br><br>        private void Reset()<br>        {<br>            ButtonReset.IsEnabled = false;<br>            TextBlockMessage.Text = string.Empty;<br><br>            Count = 0;<br>            Ellapsed = 0;<br><br>            Time = DateTimeOffset.Now;<br>            _resetTime = Time;<br><br>            _threadingTimer.Change(_period, _period);<br>        }<br><br>        private readonly static string TITLE = &quot;Clock - DispatcherTimer - VisualStudio Template Pattern&quot;;<br>        private readonly static string DEFAULT_PERIOD = &quot;1000&quot;;<br>        private readonly static string TIME_FORMAT = &quot;HH:mm:ss.f&quot;;<br>        private readonly static string COUNT_IS_NOT_EQUAL_ELLAPSED = &quot;Count({0}) is not equal to ellapsed({1}) at {2}.&quot;;<br>    }<br>}</pre><p>The key point to note is the Callback(object? state) method. Since the callback runs on a different thread than the UI thread, the callback needs the MainWindow Dispatcher to resolve thread ownership issues that arise when updating the UI (visual display). [Start without debugging]. Change the period between 1000 msec and 1 msec. You’ll notice that the decrease frequency of timer events has decreased compared to the previous project.</p><p><strong>Using Threading.Timer and the MVVM Pattern</strong></p><p>Create a WPF project with the development tools and install CommunityToolkit.Mvvm Version 8.4.0.<br>Modify App.xaml and App.xaml.cs as shown below. Also, remove [StartupUri=”MainWindow.xaml”] from the Application tag.</p><pre>&lt;Application x:Class=&quot;Clock.ThreadTimer.Mvvm.App&quot;<br>             xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;<br>             xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot;<br>             xmlns:local=&quot;clr-namespace:Clock.ThreadTimer.Mvvm&quot;&gt;<br>    &lt;Application.Resources&gt;<br>    &lt;/Application.Resources&gt;<br>&lt;/Application&gt;</pre><pre>using System.Windows;<br><br>namespace Clock.ThreadTimer.Mvvm<br>{<br>    /// &lt;summary&gt;<br>    /// Interaction logic for App.xaml<br>    /// &lt;/summary&gt;<br>    public partial class App : Application<br>    {<br>        private ViewModel? _viewModel;<br><br>        protected override void OnStartup(StartupEventArgs e)<br>        {<br>            base.OnStartup(e);<br><br>            _viewModel = new ViewModel(SynchronizationContext.Current!);<br><br>            MainWindow = new MainWindow<br>            {<br>                DataContext = _viewModel<br>            };<br><br>            MainWindow.Loaded += MainWindow_Loaded;<br>            MainWindow.Closing += MainWindow_Closing;<br><br>            MainWindow.Show();<br>        }<br><br>        private void MainWindow_Loaded(object sender, RoutedEventArgs e)<br>        {<br>            MainWindow.Loaded -= MainWindow_Loaded;<br><br>            _viewModel!.Run();<br>            _viewModel.Message = nameof(MainWindow_Loaded);<br>        }<br><br>        private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)<br>        {<br>            MainWindow.Closing -= MainWindow_Closing;<br>            _viewModel!.Stop();<br><br>            _viewModel.Message = nameof(MainWindow_Closing);<br>        }<br>    }<br>}</pre><p>Add ViewModel.cs as shown below. The code that changes the state of ResetCommand in the Callback(object? state) method requires SynchronizationContext.</p><pre>using CommunityToolkit.Mvvm.Input;<br>using CommunityToolkit.Mvvm.ComponentModel;<br><br>namespace Clock.ThreadTimer.Mvvm<br>{<br>    internal class ViewModel : ObservableObject<br>    {<br>        private readonly SynchronizationContext _context;<br>        private readonly Timer _threadingTimer;<br>        private DateTimeOffset _resetTime;<br>        private int _period;<br><br>        public ViewModel(SynchronizationContext context)<br>        {<br>            Title = TITLE;<br><br>            _context = context;<br>            _threadingTimer = new Timer(Callback, null, Timeout.Infinite, Timeout.Infinite);<br><br>            Period = DEFAULT_PERIOD;<br>            ResetCommand = new RelayCommand(Reset, CanReset);<br>        }<br><br>        public void Run()<br>        {<br>            Reset();<br>        }<br><br>        public void Stop()<br>        {<br>            _threadingTimer.Dispose();<br>        }<br><br>        public string Title { get; }<br>        public DateTimeOffset Time<br>        {<br>            get =&gt; _time;<br>            set =&gt; SetProperty(ref _time, value);<br>        }<br>        private DateTimeOffset _time;<br><br>        public long Count<br>        {<br>            get =&gt; _count;<br>            set =&gt; SetProperty(ref _count, value);<br>        }<br>        private long _count;<br><br>        public long Ellapsed<br>        {<br>            get =&gt; _ellapsed;<br>            set =&gt; SetProperty(ref _ellapsed, value);<br>        }<br>        private long _ellapsed;<br><br>        public int Period<br>        {<br>            get =&gt; _period;<br>            set<br>            {<br>                if ((value &gt; 0) &amp;&amp; (value != _period))<br>                {<br>                    SetProperty(ref _period, value);<br>                    Reset();<br>                }<br>            }<br>        }<br><br>        public string Message<br>        {<br>            get =&gt; _message;<br>            set =&gt; SetProperty(ref _message, value);<br>        }<br>        private string _message = string.Empty;<br><br>        private void Callback(object? state)<br>        {<br>            Time = DateTimeOffset.Now;<br>            Count++;<br>            Ellapsed = (Time.ToUnixTimeMilliseconds() - _resetTime.ToUnixTimeMilliseconds()) / _period;<br><br>            var notEqual = (Count != Ellapsed);<br>            if (string.IsNullOrEmpty(Message))<br>            {<br>                if (notEqual)<br>                {<br>                    Message = string.Format(COUNT_IS_NOT_EQUAL_ELLAPSED, Count, Ellapsed, Time.ToString(TIME_FORMAT));<br>                }<br>            }<br>            else<br>            {<br>                if (!notEqual)<br>                {<br>                    Message = string.Empty;<br>                }<br>            }<br><br>            _context.Post((args) =&gt;<br>            {<br>                ResetCommand.NotifyCanExecuteChanged();<br>            }, null);<br>        }<br><br>        public IRelayCommand ResetCommand { get; }<br>        private void Reset()<br>        {<br>            Count = 0;<br>            Ellapsed = 0;<br><br>            Time = DateTimeOffset.Now;<br>            _resetTime = Time;<br><br>            _threadingTimer.Change(Period, Period);<br>        }<br>        private bool CanReset()<br>        {<br>            return Count != Ellapsed;<br>        }<br><br>        private readonly static string TITLE = &quot;Clock - Threading.Timer - MVVM Pattern&quot;;<br>        private readonly static int DEFAULT_PERIOD = 1000;<br>        private readonly static string TIME_FORMAT = &quot;HH:mm:ss.f&quot;;<br>        private readonly static string COUNT_IS_NOT_EQUAL_ELLAPSED = &quot;Count({0}) is not equal to ellapsed({1}) at {2}.&quot;;<br>    }<br>}</pre><p>[Start without debugging]. You can see that it works properly.</p><p><strong>Conclusion</strong></p><p>If you’re asynchronously modifying UI state in the ViewModel of the MVVM pattern, you’ll see that SynchronizationContext is necessary.</p><p>* The copyright of this article belongs to the author. If copied by AI, please be sure to credit the source and author.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26893a2e61f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>