Backgroundworker正在冻结我的GUI

时间:2013-03-07 16:55:25

标签: c# .net backgroundworker

我有一个验证用户的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秒内在worker中启动代码。

为什么它会冻结GUI?

2 个答案:

答案 0 :(得分:4)

你明确地违背了后台工作者的目的。

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

答案 1 :(得分: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;
    }
}