Making UI Thread wait using Thread.sleep

前端 未结 2 1233
一向
一向 2021-01-21 15:10

I have written this code in C# for WP7 :

public void btn_handler(object sender, EventArgs args)
    {
        Button btn_Pressed = (Button)sender;
        Image         


        
相关标签:
2条回答
  • 2021-01-21 15:59

    You should never ever block the UI thread by calling Thread.Sleep.

    I think that the best solution is to create a storyboard in your XAML that will perform the required visual changes. Your button click event handler should then simply call Begin on the storyboard.

    0 讨论(0)
  • 2021-01-21 16:07

    You current approach is incorrect. It is keeping the UI thready busy. It updates the UI when it gets free.

    Here is what is happening

    Button Gets click. UI thread change the button background to Images. Then it sleeps for 5 secs and then it changes the background to white. Note that UI thread is still busy. It will only update the actual UI when it will be free. Once it has changed back color to white it gets free and updates the UI and you see the change on screen.

    You need to do this

     //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);
        }
    
    0 讨论(0)
提交回复
热议问题