使用Thread.sleep使UI线程等待
我在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 ie 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
。