C# WPF Update Label before and after processing - immediately

Michael Delfser

I have already tried several online examples (Thread, Dispatcher, await/async) but none is working for me in my C#/WPF project.

I have the following button click method:

private void BtnInstall_Click(object sender, RoutedEventArgs e) 
    {
        this.lblResponse.Content = "";

        executeInstall(); //do some work

        this.lblResponse.Content = "DONE";
    }

The label gets updated afterwards to DONE, but when I click again on the button the label isnt getting emptied before the processing of executeInstall. As I mentioned I already tried several different examples from other questions (Dispatcher.BeginInvoke, Thread, Task, await/async) but none of them has worked - the label change before is never done before the processing of executeInstall.

I am working in .NET framework 4.7.2.

Is there maybe a setting that debug mode only executes the program with one thread and thats maybe why none of the solutions works for me?

Neil B

Use async for that.

private async void BtnInstall_Click(object sender, RoutedEventArgs e)
{
    this.lblResponse.Content = "";

    await Task.Run(()=> executeInstall());

    this.lblResponse.Content = "DONE";
}

UPDATE: If you need to access the UI inside your executeIntall method you will need to invoke the Dispatcher. In this case you would need to delay the Task to give the label time to update before the install starts. Note that this will cause the UI to freeze during the entire install.

private async void BtnInstall_Click(object sender, RoutedEventArgs e)
{
    lblResponse.Content = "starting...";

    await Task.Delay(100).ContinueWith(_=>
    {
        App.Current.Dispatcher.Invoke(() =>
        {
            executeInstall();
            lblResponse.Content = "DONE";
        });
    });
}

A better approach would be to only call the dispatcher when it's actually needed. This would keep the UI responsive during the entire process.

private async void BtnInstall_Click(object sender, RoutedEventArgs e)
{
    lblResponse.Content = "starting...";
    await Task.Run(()=> executeInstall());
    lblResponse.Content = "DONE";
}

private void executeInstall()
{
    Thread.Sleep(1000); //do time consuming operation
    App.Current.Dispatcher.Invoke(() => lblResponse.Content = "Downloading Files...");
    Thread.Sleep(1000); //do time consuming operation
    App.Current.Dispatcher.Invoke(() => lblResponse.Content = "Unzipping Files...");
    Thread.Sleep(1000); //do time consuming operation
    App.Current.Dispatcher.Invoke(() => lblResponse.Content = "Updating Files...");
    Thread.Sleep(1000); //do time consuming operation
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related