From ff9c9c7b55ac52d7c26dd5cead6586c2c651a8fe Mon Sep 17 00:00:00 2001 From: Tracy Pearson Date: Fri, 12 Aug 2022 12:30:18 -0400 Subject: [PATCH] Get the dispatcher before the Task. --- WpfViewModelFirst/MainWindowViewModel.cs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/WpfViewModelFirst/MainWindowViewModel.cs b/WpfViewModelFirst/MainWindowViewModel.cs index 1d5d423..b1f7231 100644 --- a/WpfViewModelFirst/MainWindowViewModel.cs +++ b/WpfViewModelFirst/MainWindowViewModel.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows.Input; using System.Windows.Threading; @@ -23,22 +24,22 @@ namespace WpfViewModelFirst { CurrentViewModel = null; CurrentViewModel = new Part1ViewModel(Part1Action); -// MainFrameViewModel = new Part2ViewModel(); + // MainFrameViewModel = new Part2ViewModel(); } private void Part1Action() { + var currentDispatcher = Dispatcher.CurrentDispatcher; CurrentViewModel = null; - Task delay = Task.Run(LongDelay).ContinueWith(c => + Task delay = Task.Run(LongDelay).ContinueWith(c => { System.Diagnostics.Debug.WriteLine(c.Result); CurrentViewModel = new Part2ViewModel(); - Strings.Add($"{DateTime.Now}"); + currentDispatcher.Invoke(() => + { + Strings.Add($"{DateTime.Now}"); + } + ); }, TaskContinuationOptions.OnlyOnRanToCompletion); - //Task.Run(async () => await LongDelay()).ContinueWith(c => - // { - // System.Diagnostics.Debug.WriteLine(c.Result); - //CurrentViewModel = new Part2ViewModel(); - //}, TaskContinuationOptions.OnlyOnRanToCompletion); } private async Task LongDelay()