Why does Thread.Sleep() freeze the Form?

前端 未结 6 878
忘掉有多难
忘掉有多难 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 03:58

    EDIT: After programming for a few more years, I now know how terrible of a practice this is. DO NOT DO ANYTHING I SUGGESTED BELOW. It's all crap. A more proper solution would be doing all of your intensive methods async all together. Regardless, don't do what I mention below.

    All The methods above do work however, I do recommend just using an async void.
    Sleep() just pauses the current thread for int amount of milliseconds, and if your whole program runs off of 1 thread, it'll pause the whole program. Don't quote me on this, I do believe that async creates a new thread specifically for that function.

    Below I've included a better sleep function.

    To call the function asleep(milliseconds), replace "milliseconds" with how many milliseconds you wish to sleep for.

    Function Code:

    public async void asleep(int time){
        await Task.Delay(time)
    }
    

提交回复
热议问题