2013-03-07 109 views
0

我有一个验证用户的WPF应用程序。当该用户成功通过身份验证后,界面会更改并向用户致意。我希望欢迎消息在5秒内出现,然后使用其他内容进行更改。这是我的欢迎消息启动BackgroundWorkerBackgroundworker冻结我的GUI

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?

+2

你觉得呢'uiCurrent.Post'是干什么的? – SLaks 2013-03-07 16:57:59

回答

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; 
    } 
} 
+0

完全一样!我需要uiCurrent,因为如果没有,另一个线程(主要的)拥有它,我不能修改它们。但是,我解决了这个问题!非常感谢! PS:当我被允许的时候,我会把你的答案作为好的答复。 – Sonhja 2013-03-07 17:02:05

4

你明确地打败了后台工作者的目的。

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