Exit flow automatically when closing WPF application

I have a main WPF window, and one of its controls is the user control I created. This user control is an analog clock and contains a stream that updates hours, minutes, and seconds. Originally it was not a thread, it was a timer event that updated the hour, minutes and seconds, but I changed it to a thread because the application does some kind of hard work when the user presses the start button and then the clock will not update, so I changed it to a stream.

WPF window code snippet:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:GParts" xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes assembly=PresentationFramework.Aero" xmlns:UC="clr-namespace:GParts.UserControls" x:Class="GParts.WinMain" Title="GParts" WindowState="Maximized" Closing="Window_Closing" Icon="/Resources/Calendar-clock.png" x:Name="WMain" > <...> <!-- this is my user control --> <UC:AnalogClock Grid.Row="1" x:Name="AnalogClock" Background="Transparent" Margin="0" Height="Auto" Width="Auto"/> <...> </Window> 

My problem is that when the user exits the application, the thread seems to continue to execute. I want the thread to end automatically when the main windows close.

User Management Designer Code Snippet:

 namespace GParts.UserControls { /// <summary> /// Lógica de interacción para AnalogClock.xaml /// </summary> public partial class AnalogClock : UserControl { System.Timers.Timer timer = new System.Timers.Timer(1000); public AnalogClock() { InitializeComponent(); MDCalendar mdCalendar = new MDCalendar(); DateTime date = DateTime.Now; TimeZone time = TimeZone.CurrentTimeZone; TimeSpan difference = time.GetUtcOffset(date); uint currentTime = mdCalendar.Time() + (uint)difference.TotalSeconds; christianityCalendar.Content = mdCalendar.Date("d/e/Z", currentTime, false); // this was before implementing thread //timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed); //timer.Enabled = true; // The Work to perform ThreadStart start = delegate() { // With this condition the thread exits when main window closes but // despite of this it seems like the thread continues executing after // exiting application because in task manager cpu is very busy // while ((this.IsInitialized) && (this.Dispatcher.HasShutdownFinished== false)) { this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { DateTime hora = DateTime.Now; secondHand.Angle = hora.Second * 6; minuteHand.Angle = hora.Minute * 6; hourHand.Angle = (hora.Hour * 30) + (hora.Minute * 0.5); DigitalClock.CurrentTime = hora; })); } Console.Write("Quit ok"); }; // Create the thread and kick it started! new Thread(start).Start(); } // this was before implementing thread void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() => { DateTime hora = DateTime.Now; secondHand.Angle = hora.Second * 6; minuteHand.Angle = hora.Minute * 6; hourHand.Angle = (hora.Hour * 30) + (hora.Minute * 0.5); DigitalClock.CurrentTime = hora; })); } } // end class } // end namespace 

How can I automatically exit the stream when the main window closes and then the application exits?

+4
source share
5 answers

Just set the IsBackground property for the stream to true so that it does not prevent the process from terminating.

 Thread t = new Thread(...) { IsBackground = true }; 
+11
source

Well, one serious problem you are facing is that you run an endless loop that queues up a lot of dispatcher jobs to update your clock, constantly and quickly. An easy fix might be to put a Thread.Sleep(1000); statement Thread.Sleep(1000); loop and then make your thread a background thread, as Taylor suggests.

In any case, I am a little surprised that background work may cause the timer to fail to update. Obtaining such an approach would be an ideal solution. Perhaps try DispatcherTimer and see if they can make updates while the background is running.

+1
source

Maybe using DependecyProperty in your watch model http://www.wpftutorial.net/HowToCreateADepProp.html DependecyProperty is faster than the INotifyPropertyChanget interface, so this may be useful to you http://blog.lexique-du-net.com /index.php?post/2010/02/24/DependencyProperties-or-INotifyPropertyChanged

0
source

Finally, I mixed two solutions: RandomEngy and Taylor, but it did not work fine (the application was not completed successfully), so I decided to combine them with another solution in the stream:

wpf cancel background worker on application output

I am the main window application, from XAML I set the ShutdownMode property of my application to OnMainWindowClose, as Thomas said in his comment.

Thanks!

0
source

I know that you solved your problem, but since I had a similar problem with the current thread and exiting the application, I thought that I would share how I solved my problem.

I ended up crawling the used dispatcher / thread model, instead decided to use the BackgroundWorker class (System.ComponentModel.BackgroundWorker). It was a simple four-step process:

  • create a private element for storing BackgroundWorker
  • to assign BackgroundWorker.DoWork event handler in ctor
  • define a DoWork event handler method
  • call _myBackgroundWorker.RunWorkAsync () when I want to disable the actual work.

The following is information about using BackgroundWorker, which is built into this article about using dispatcher in WPF .

Hope this helps someone ...

0
source

Source: https://habr.com/ru/post/1304617/


All Articles