Search code examples
c#wpfwhile-looptextblock

WPF UI keeps freezing during while loop


During this code my UI freezes and doesn't update like i would like although the console write line works perfectly so im sure it is going through the loop exactly how i want

while (true)
            {
                MyMethod();

            }


            void MyMethod() {
                Console.WriteLine(DateTime.Now);


                TimeSpan duration = SetDate - DateTime.Now;

                int days = duration.Days + 1;
                string strDays = days.ToString();

                string LeftorAgo = "";
                if (strDays[0] == '-')
                {

                    LeftorAgo = "ago";
                }
                else
                {
                    LeftorAgo = "left";
                }

                this.Dispatcher.Invoke(() =>
                {
                    ShowDate.Text = $"{strDays.TrimStart('-')}\n days {LeftorAgo}";
                    ShowSubject.Text = Subject;
                });
                System.Threading.Thread.Sleep(5000);

            }

Edit with Darkonekt's help i solved this issue using his timer technique and it works perfectly thank you! code below

 private System.Windows.Threading.DispatcherTimer remainTimer = new System.Windows.Threading.DispatcherTimer();

InitializeComponent();

            remainTimer.Tick += new EventHandler(MyMethod);
            remainTimer.Interval = TimeSpan.FromSeconds(5);
            remainTimer.Start();



            void MyMethod(object sender, EventArgs e) {
                ...

thank you for your help


Solution

  • Use a DispatcherTimer instead of while loop:

        private DispatcherTimer remainTimer = new DispatcherTimer();
    
        public MainWindow()
        {
            InitializeComponent();
    
            remainTimer.Tick += MyMethod;
            remainTimer.Interval = TimeSpan.FromSeconds(5);
            remainTimer.Start();
        }
    
        private void MyMethod(object sender, EventArgs e)
        {
            Console.WriteLine(DateTime.Now);
    
            TimeSpan duration = SetDate - DateTime.Now;
    
            int days = duration.Days + 1;
            string strDays = days.ToString();
    
            string LeftorAgo = "";
            if (strDays[0] == '-')
            {
    
                LeftorAgo = "ago";
            }
            else
            {
                LeftorAgo = "left";
            }
    
            ShowDate.Text = $"{strDays.TrimStart('-')}\n days {LeftorAgo}";
            ShowSubject.Text = Subject;
        }