c# - 立即更新 UI 线程

标签 c# wpf multithreading

我正在尝试在登录时启用繁忙指示器。我遇到的问题是在所有操作完成之前它不会启用。如何在我登录后立即告诉线程更新 UI 以尽快启动指标?

    private void LoginButton_Click(object sender, RoutedEventArgs e)
    {
        this.Dispatcher.Invoke((Action)(() =>
        {
            radBusyIndicator.IsBusy = true;
            //var backgroundWorker = new System.ComponentModel.BackgroundWorker();
            //backgroundWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(backgroundWorker_DoWork);
            //backgroundWorker.RunWorkerAsync();
        }));

        string error = string.Empty;
        long userId = 0;

        //Login code here....
        //...........  bunch of other code. etc..

     }

最佳答案

只要 UI 线程空闲,UI 就会更新。在这种情况下不需要 Dispatcher.Invoke,因为您已经在 UI 线程中。

这里的关键是将“工作”移到后台线程中,即:

private void LoginButton_Click(object sender, RoutedEventArgs e)
{
    radBusyIndicator.IsBusy = true;
    LoginButton.IsEnabled = false; // Prevent clicking twice

    string error = string.Empty;
    long userId = 0;

    // Start this in the background
    var task = Task.Factory.StartNew(()=>
    {
        //Login code here....
        //...........  bunch of other code. etc..
    });

    // Run, on the UI thread, cleanup code afterwards
    task.ContinueWith(t =>
    {
        // TODO: Handle exceptions by checking t.Exception or similar...

        radBusyIndicator.IsBusy = false;
        LoginButton.IsEnabled = true;
    }, TaskScheduler.FromCurrentSynchronizationContext());
 }

如果您使用的是 C# 5,则可以通过使登录和其他代码异步来简化此过程:

private async void LoginButton_Click(object sender, RoutedEventArgs e)
{
    radBusyIndicator.IsBusy = true;
    LoginButton.IsEnabled = false; // Prevent clicking twice

    long userId = 0;

    // Call async method with await, etc...
    string error = await DoLoginAsync(userId);

    var result = await BunchOfOtherCodeAsync();

    radBusyIndicator.IsBusy = false;
    LoginButton.IsEnabled = true;
 }

关于c# - 立即更新 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17352982/

相关文章:

c# - 在 C# 中访问变量是原子操作吗?

c# - 将 FlowDocument 转换为 PDF 的最佳方式是什么

c# - C#中快速匹配DataTable和String Array的方法

c# - WPF DataGrid 动态列绑定(bind)

wpf - .net wpf4 应用程序的 Locbaml 本地化

VB.NET 多线程,阻塞线程直到收到通知

c# - 字典在后台加载

c# - 仅当调用Application.Run()WPF应用程序时,代码才会启动

c# - 使用 TreeInstance 将树添加到 Terrain C#

c# - 将 WPF 控件绑定(bind)到 Timer 中更新的数据是否安全?