I have this xaml
<Window x:Class="TestCloseWindow.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Width="500" Height="400">
<StackPanel>
<TextBlock x:Name="Seconds"></TextBlock>
<Button Content="fasdfd" Click="ButtonBase_OnClick"></Button>
</StackPanel>
</Window>
And this code
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
}
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
await CountToTen();
}
private Task CountToTen()
{
return Task.Factory.StartNew
(() =>
{
for (var i = 1; i <= 10; i++)
{
Seconds.Text = i.ToString(CultureInfo.InvariantCulture);
Task.Delay(1000).Wait();
}
}
, CancellationToken.None
, TaskCreationOptions.None
, TaskScheduler.FromCurrentSynchronizationContext()
);
}
}
In this code I use TaskScheduler.FromCurrentSynchronizationContext() in order to access UI from background Task.
I expected that I can see how program count to ten, but instead of it I see blocked UI for 10 seconds and after 10 in TextBlock
How can I fix it?