简体   繁体   中英

WPF update UI from async method

In public MainWindow() I call TestTask3(10000); . A TextBlock Text is bound to Answer in the XAML. The get is called and the initial value is displayed. I see the set call NotifyPropertyChanged. But the get is not called a second time to get the new value. I also have a button that changes Answer and that does change the TextBlock.

How to fix this or another approach? I want to keep the UI reactive and update some UI elements after a delay.

private int answser = -2;
public int Answer
{
    get { return answser; }
    set
    {
        if (answser != value)
        {
            answser = value;
            NotifyPropertyChanged("Answer");
        }
    }
}
public async void TestTask3(int delay)
{
    Debug.WriteLine($"TestTask3");
    int answer = -1;
    int i = await Task.Run(() =>
    {
        // … do compute-bound work here  
        Task.Delay(delay);
        answer = -1;
        return answer;
    });
    Debug.WriteLine($"TestTask3   {i}");
    Answer = answer;
    //return answer;
}

Task.Delay(delay) is awaitable method.

Following solution works for me. I took a long loop calculation and it returns me result on UI after 10 seconds. Tested and working.

public async void TestTask3(int delay)
{
    int answer = -1;
    int i = await Task.Run(async () =>
    {
        // … do compute-bound work here  
        for (int j = 0; j < 100000000; j++)
        {
            answer += j;
        }

        await Task.Delay(delay);

        //answer = -1;
        return answer;
    });
    Answer = answer;
    //return answer;
}

Usage:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    await TestTask3(10000);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM