33// See the LICENSE file in the project root for more information.
44
55using System ;
6+ using System . Threading ;
67using System . Threading . Tasks ;
78using System . Windows ;
89using System . Windows . Input ;
@@ -17,6 +18,7 @@ public partial class MessageDialog : BaseMetroDialog
1718 {
1819 private const string ACCENT_BUTTON_STYLE = "MahApps.Styles.Button.Dialogs.Accent" ;
1920 private const string ACCENT_HIGHLIGHT_BUTTON_STYLE = "MahApps.Styles.Button.Dialogs.AccentHighlight" ;
21+ private CancellationTokenRegistration cancellationTokenRegistration ;
2022
2123 /// <summary>Identifies the <see cref="Message"/> dependency property.</summary>
2224 public static readonly DependencyProperty MessageProperty = DependencyProperty . Register ( nameof ( Message ) , typeof ( string ) , typeof ( MessageDialog ) , new PropertyMetadata ( default ( string ) ) ) ;
@@ -136,7 +138,7 @@ internal Task<MessageDialogResult> WaitForButtonPressAsync()
136138 }
137139 } ) ) ;
138140
139- TaskCompletionSource < MessageDialogResult > tcs = new TaskCompletionSource < MessageDialogResult > ( ) ;
141+ var tcs = new TaskCompletionSource < MessageDialogResult > ( ) ;
140142
141143 RoutedEventHandler negativeHandler = null ;
142144 KeyEventHandler negativeKeyHandler = null ;
@@ -152,15 +154,7 @@ internal Task<MessageDialogResult> WaitForButtonPressAsync()
152154
153155 KeyEventHandler escapeKeyHandler = null ;
154156
155- Action cleanUpHandlers = null ;
156-
157- var cancellationTokenRegistration = this . DialogSettings . CancellationToken . Register ( ( ) =>
158- {
159- cleanUpHandlers ? . Invoke ( ) ;
160- tcs . TrySetResult ( this . ButtonStyle == MessageDialogStyle . Affirmative ? MessageDialogResult . Affirmative : MessageDialogResult . Negative ) ;
161- } ) ;
162-
163- cleanUpHandlers = ( ) =>
157+ Action cleanUpHandlers = ( ) =>
164158 {
165159 this . PART_NegativeButton . Click -= negativeHandler ;
166160 this . PART_AffirmativeButton . Click -= affirmativeHandler ;
@@ -174,9 +168,20 @@ internal Task<MessageDialogResult> WaitForButtonPressAsync()
174168
175169 this . KeyDown -= escapeKeyHandler ;
176170
177- cancellationTokenRegistration . Dispose ( ) ;
171+ this . cancellationTokenRegistration . Dispose ( ) ;
178172 } ;
179173
174+ this . cancellationTokenRegistration = this . DialogSettings
175+ . CancellationToken
176+ . Register ( ( ) =>
177+ {
178+ this . BeginInvoke ( ( ) =>
179+ {
180+ cleanUpHandlers ( ) ;
181+ tcs . TrySetResult ( this . ButtonStyle == MessageDialogStyle . Affirmative ? MessageDialogResult . Affirmative : MessageDialogResult . Negative ) ;
182+ } ) ;
183+ } ) ;
184+
180185 negativeKeyHandler = ( sender , e ) =>
181186 {
182187 if ( e . Key == Key . Enter )
0 commit comments