【问题标题】:C# WPF Update Label before and after processing - immediately处理前后的 C# WPF 更新标签 - 立即
【发布时间】:2023-04-04 22:28:02
【问题描述】:

我已经尝试了几个在线示例(Thread、Dispatcher、await/async),但在我的 C#/WPF 项目中没有一个对我有用。

我有如下按钮点击方法:

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

        executeInstall(); //do some work

        this.lblResponse.Content = "DONE";
    }

标签在之后更新为 DONE,但是当我再次单击按钮时,标签在执行安装处理之前没有被清空。 正如我所提到的,我已经尝试了来自其他问题的几个不同示例(Dispatcher.BeginInvoke、Thread、Task、await/async),但它们都没有奏效——之前的标签更改从未在 executeInstall 处理之前完成。

我正在使用 .NET 框架 4.7.2。

是否存在调试模式仅使用一个线程执行程序的设置,这可能是为什么没有一个解决方案适合我?

【问题讨论】:

  • 异步等待是您的解决方案

标签: c# wpf multithreading user-interface


【解决方案1】:

为此使用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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多