Why does Thread.Sleep() freeze the Form?

前端 未结 6 874
忘掉有多难
忘掉有多难 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:10

    Thread.Sleep just sleeps the current thread (i.e. stops it from doing anything, such as redrawing, processing clicks etc), which in your case is the UI thread. If you put the Sleep in DoStuff you wouldn't experience the block as you'd be on a separate thread although you wouldn't be able to update button1. Depending on the version of .NET you're using consider using the Task Parallel Library, something like this:

    private TaskScheduler _uiScheduler;
    public Form1()
    {
        InitializeComponent();
        _uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
    
        Thread thread1 = new Thread(DoStuff);
        thread1.Start();
    
        // Create a task on a new thread.
        Task.Factory.StartNew(() =>
            {
                for (int i = 0; i < 100000; i++)
                {
                    Thread.Sleep(500);
    
                    // Create a new task on the UI thread to update the button
                    Task.Factory.StartNew(() =>
                        { button1.Text += "."; }, CancellationToken.None, TaskCreationOptions.None, _uiScheduler);
                }
            });
    }
    

提交回复
热议问题