2013-03-07 75 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線程,並執行所有操作。