使用Thread.sleep使UI线程等待

时间:2012-01-03 09:24:13

标签: c# windows-phone-7.1

我已在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,但我不明白如何继续。请帮忙:(

2 个答案:

答案 0 :(得分:5)

您当前的方法不正确。它保持了用户界面的繁忙。它在获得免费时更新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);
    }

答案 1 :(得分:3)

您永远不应该通过调用Thread.Sleep来阻止UI线程。

我认为最好的解决方案是在XAML中创建一个storyboard来执行所需的视觉更改。然后,您的按钮点击事件处理程序应该只是在故事板上调用Begin