处理之前和之后的C#WPF更新标签-立即

我已经尝试了几个在线示例(线程,调度程序,等待/异步),但是在我的C#/ WPF项目中没有一个对我有用。

我有以下按钮单击方法:

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

        executeInstall(); //do some work

        this.lblResponse.Content = "DONE";
    }

此后标签将更新为DONE,但是当我再次单击按钮时,在执行executeInstall之前标签不会被清空。 正如我提到的那样,我已经尝试过其他问题(Dispatcher.BeginInvoke,Thread,Task,await / async)中的几个不同示例,但是它们都没有起作用-之前的标签更改从未在执行executeInstall之前完成。

我正在.NET Framework 4.7.2中工作。

是否存在一个设置,即调试模式仅使用一个线程执行程序,这也许就是为什么没有一种解决方案对我有用的原因?

qwertyu1212121 回答:处理之前和之后的C#WPF更新标签-立即

为此使用async

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

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

    this.lblResponse.Content = "DONE";
}

更新:如果您需要在executeIntall方法内访问UI,则需要调用Dispatcher。在这种情况下,您需要延迟Task来给标签时间在安装开始之前进行更新。请注意,这将导致UI在整个安装过程中冻结。

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";
        });
    });
}

更好的方法是仅在实际需要时才调用调度程序。这将使UI在整个过程中保持响应。

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
}
本文链接:https://www.f2er.com/3106207.html

大家都在问