【问题标题】:Backgroundworker is freezing my GUIBackgroundworker 正在冻结我的 GUI
【发布时间】:2013-03-07 16:55:25
【问题描述】:

我有一个验证用户的 WPF 应用程序。当该用户成功通过身份验证时,界面会更改并向用户打招呼。我希望欢迎消息在 5 秒内出现,然后用其他内容更改。这是我启动 BackgroundWorker 的欢迎消息:

LabelInsertCard.Content = Cultures.Resources.ATMRegisterOK + " " + user.Name;
ImageResult.Visibility = Visibility.Visible;
ImageResult.SetResourceReference(Image.SourceProperty, "Ok");
BackgroundWorker userRegisterOk = new BackgroundWorker
   {
        WorkerSupportsCancellation = true,
        WorkerReportsProgress = true
   };
userRegisterOk.DoWork += userRegisterOk_DoWork;
userRegisterOk.RunWorkerAsync();

这是我的BackgroundWorker,延迟五秒:

void userRegisterOk_DoWork(object sender, DoWorkEventArgs e)
    {
        if (SynchronizationContext.Current != uiCurrent)
        {
            uiCurrent.Post(delegate { userRegisterOk_DoWork(sender, e); }, null);
        }
        else
        {
            Thread.Sleep(5000);

            ImageResult.Visibility = Visibility.Hidden;
            RotatoryCube.Visibility = Visibility.Visible;
            LabelInsertCard.Content = Cultures.Resources.InsertCard;
        }
    }

但是 Backgroundworker 冻结了我的 GUI 5 秒钟。显然,我想做的是在欢迎消息 5 秒后在工作人员内部启动代码。

为什么会冻结 GUI?

【问题讨论】:

  • 你认为uiCurrent.Post在做什么?

标签: c# .net backgroundworker


【解决方案1】:

你明显违背了后台工作人员的目的。

您的代码在回调中切换回 UI 线程并在那里执行所有操作。

【讨论】:

    【解决方案2】:

    也许这就是你想要的:

    void userRegisterOk_DoWork(object sender, DoWorkEventArgs e)
    {
        if (SynchronizationContext.Current != uiCurrent)
        {
            // Wait here - on the background thread
            Thread.Sleep(5000);
            uiCurrent.Post(delegate { userRegisterOk_DoWork(sender, e); }, null);
        }
        else
        {
            // This part is on the GUI thread!!
            ImageResult.Visibility = Visibility.Hidden;
            RotatoryCube.Visibility = Visibility.Visible;
            LabelInsertCard.Content = Cultures.Resources.InsertCard;
        }
    }
    

    【讨论】:

    • 就是这样!我需要 uiCurrent 因为如果没有,另一个线程(主线程)拥有它,我无法修改它们。但有了这个我解决了!非常感谢! PS:当我被允许时,我会将您的答案作为好的答案发布。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多