Why does Thread.Sleep() freeze the Form?

前端 未结 6 875
忘掉有多难
忘掉有多难 2021-01-22 03:38

I try to experiment with Thread.Sleep(). I created basic Windows Forms application with one button.

    private void button1_Click(object sender, Ev         


        
6条回答
  •  礼貌的吻别
    2021-01-22 04:06

    Re-arrange code as following

    private void button1_Click(object sender, EventArgs e)
    {
            Thread thread1 = new Thread(DoStuff);
            thread1.Start();
    }
    
    public void DoStuff()
    {     
            for (int i = 0; i < 100000; i++)
            {
                Thread.Sleep(500);
                //Invoke goes here
            }
    }
    

    Now you run your WORK in a separate thread and release your UI thread for usual work (Drawing related or other work)

    NOTE - Now you will need Invoke methods to change Button text , else you will get warning for "Cross-thread operation not valid"

    More on Invokes - How to update the GUI from another thread in C#?

提交回复
热议问题