Jeet Parekh
Jeet Parekh

Reputation: 740

Thread.Sleep() not working as expected in WPF application

I've been learning WPF. I tried using Threading in my WPF application, but I think I missed something.

I've placed a button and a label in the window. If I press the button, I want the label to change it's background color... after 2 seconds, set the original background color.

Here's the XAML and the code that I've been trying.

MainWindow.XAML

<Window x:Class="UITest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:UITest"
        mc:Ignorable="d"
        Title="MainWindow" Height="519" Width="656">
    <StackPanel>
        <Button x:Name="button1" Width="60" Height="30" Content="Button" Margin="10 10 0 0" BorderThickness="0" BorderBrush="{x:Null}" Padding="0" HorizontalAlignment="Left" VerticalAlignment="Top">
        </Button>

        <Label x:Name="label1" Width="100" Height="30" Margin="10 10 0 0" BorderThickness="0" BorderBrush="{x:Null}" Padding="0" HorizontalAlignment="Left" VerticalAlignment="Top" Background="Bisque">
        </Label>
    </StackPanel>
</Window>

MainWindow.XAML.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace UITest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.button1.Click += Button1_Click;
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            label1.Background = Brushes.Black;
            Thread.Sleep(2000);
            label1.Background = Brushes.Bisque;
        }
    }
}

Upvotes: 0

Views: 2281

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 38046

You are blocking UI thread. Try this instead:

private async void Button1_Click(object sender, RoutedEventArgs e)
    {
        label1.Background = Brushes.Black;
        await Task.Delay(2000);
        label1.Background = Brushes.Bisque;
    }

Upvotes: 6

Related Questions