Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DispatcherTimer pauses when minimizing/maximizing/closing window

Tags:

c#

wpf

I try to explain my problem on simple app:

I have MainWindow with just one TextBlock. Property Text of this TextBlock is binded to property Seconds of my class CTimer. In MainWindow I also have a DispatcherTimer doing one simple thing every second - increments Seconds property of my object.

MainWindow.xaml:

<Window x:Class="Try.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock Name="txtTime" Text="{Binding Seconds}" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="16" FontWeight="Bold"/>
    </Grid>
</Window>

MainWindow.xaml.cs:

public partial class MainWindow : Window
{
    private CTimer timer = new CTimer();
    private DispatcherTimer ticker = new DispatcherTimer();

    public MainWindow()
    {
        InitializeComponent();

        ticker.Tick += AddSeconds;
        ticker.Interval = TimeSpan.FromSeconds(1);
        txtTime.DataContext = timer;

        ticker.Start();
    }

    public void AddSeconds(object sender, EventArgs e) 
    {
        timer.Seconds++;
    }
}

CTimer.cs:

public class CTimer:INotifyPropertyChanged
{
    private int seconds = 0;

    public int Seconds
    {
        get { return seconds; }
        set 
        { 
            seconds = value;
            OnPropertyChanged("Seconds");
        }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }

    #endregion
}

My problem - when I press whichever of three window buttons (min/max/close) and keep it pressed, the DispatcherTimer pauses and stays paused until I release the pressed button.

Do somebody know the cause of this behaviour?

like image 921
flipis Avatar asked Jan 13 '23 10:01

flipis


1 Answers

As long as you press one of these buttons, the UI-Thread is blocked. Because its a DispatcherTimer, it belongs to the Window's Dispatcher and runs in the same thread. So if this thread is blocked, the DispatcherTimer stops running.

You could use the System.Timers.Timer. The UI wont get updated as long as you hold one of the three window buttons, but the timer will keep running.

like image 62
Florian Gl Avatar answered Jan 31 '23 00:01

Florian Gl