[英]Making UI Thread wait using Thread.sleep
我用C#為WP7編寫了這段代碼:
public void btn_handler(object sender, EventArgs args)
{
Button btn_Pressed = (Button)sender;
ImageBrush br = new ImageBrush();
br.ImageSource = new BitmapImage(new Uri("/images/cat.png"
, UriKind.Relative));
btn_Pressed.Background = br;
Thread.Sleep(5000);
SolidColorBrush sBrush = new SolidColorBrush();
sBrush.Color = System.Windows.Media.Colors.White;
btn_Pressed.Background = sBrush;
}
每當用戶單擊按鈕時,我希望按鈕的背景更改為圖像。 大約5秒后,我希望背景變回白色。 目前,該程序不會更改按鈕的背景圖像,它會等待5秒鍾並直接將背景更改為白色。
我是WP的菜鳥。 我試圖尋找一個解決方案,我得到的是創建一個DispatcherThread,但我不明白如何繼續。 請幫忙 :(
您當前的方法是不正確的。 它保持了用戶界面的繁忙。 它在獲得免費時更新UI。
這是正在發生的事情
按鈕獲取單擊。 UI線程將按鈕背景更改為圖像。 然后它睡了5秒然后它將背景變為白色。 請注意,UI線程仍然很忙。 它只會在免費時更新實際用戶界面。 一旦它將顏色變回白色就會自由並更新UI,您會在屏幕上看到更改。
你需要這樣做
//inside the button click event create a background worker
BackgroundWorker worker = new BackgroundWorker();
worker.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
Button btn_Pressed = (Button)sender;
ImageBrush br = new ImageBrush();
br.ImageSource = new BitmapImage(new Uri("/images/cat.png", UriKind.Relative));
btn_Pressed.Background = br;
public static void worker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
//once backgroudn work i.e. DoWork is complete this method will be
//called and code below will execute in UI thread
SolidColorBrush sBrush = new SolidColorBrush();
sBrush.Color = System.Windows.Media.Colors.White;
btn_Pressed.Background = sBrush;
}
public static void worker_DoWork(object sender, DoWorkEventArgs e)
{
//it will wait 5 secs in the background thread
Thread.Sleep(5000);
}
您永遠不應該通過調用Thread.Sleep
阻止UI線程。
我認為最好的解決方案是在XAML中創建一個能夠執行所需視覺更改的故事板 。 然后,您的按鈕單擊事件處理程序應該只在故事板上調用Begin
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.