C# 异步操作解决界面卡顿假死(Application.DoEvents())

提出问题

按钮事件增加休眠代码,模拟耗时操作,导致界面卡死

private  void button1_Click(object sender, EventArgs e)
{
    int i = 0;
    while (true)
    {
        Thread.Sleep(20);
        i++;
        if (i > 8000) return;
    }

}

解决

使用下面代码解决:

Application.DoEvents();

解释

处理当前在消息队列中的所有 Windows 消息。

交出CPU控制权,让系统可以处理队列中的所有Windows消息
比如在大运算量循环内,加 Application.DoEvents()可以防止界面停止响应

因为winform的消息循环是一个线程来处理,那么假如你的某个操作比较耗时,那么消息处理得等你这个耗时操作做完了才能继续,而 Application.DoEvents 方法就是允许你在耗时操作的内部调用它,而去处理消息队列中的消息。

官网解释:
https://learn.microsoft.com/zh-cn/dotnet/api/system.windows.forms.application.doevents?view=windowsdesktop-7.0

注意

这种方式相对简单,但不能随意使用,因为效率比较低下

数据多,耗时长时,一般使用 多线程异步解决

例子

private  void button1_Click(object sender, EventArgs e)
{
    int i = 0;
    while (true)
    {
        Thread.Sleep(20);
        Application.DoEvents();
        i++;
        if (i > 8000) return;
    }
}

进度条假死

使用进度条时,使用该代码,也可以解决进度条假死

参考:
https://blog.csdn.net/gy0124/article/details/120778146
https://blog.csdn.net/sinat_23338865/article/details/52596818