0

我有一个验证用户的 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 秒启动工作人员内部的代码。

为什么会冻结 GUI?

4

2 回答 2

4

您明确破坏了后台工作人员的目的。

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

于 2013-03-07T16:57:33.927 回答
3

也许这就是你想要的:

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;
    }
}
于 2013-03-07T17:00:00.763 回答