Application.DoEvents() 处理队列消息,防界面假死

private void button1_Click(object sender, EventArgs e)
        {
            //MyMethod my = method;
            //IAsyncResult asyncResult = my.BeginInvoke(MethodCompleted, my);
            //Visible控件属性
            while (Visible)
            {
                for (int rgb = 0; rgb < 254 && Visible; rgb++)
                {
                    this.BackColor = Color.FromArgb(rgb, 255 - rgb, rgb);
                    /*
                     * 当运行 Windows 窗体时,它将创建新窗体,然后该窗体等待处理事件。
                     * 该窗体在每次处理事件时,均将处理与该事件关联的所有代码。
                     * 所有其他事件在队列中等待。在代码处理事件时,应用程序并不响应。
                     * 例如,当将另一窗口拖到该窗口前面时,该窗口不重新绘制。
                     * 如果在代码中调用 DoEvents,则您的应用程序可以处理其他事件。          
                     */
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                }
                //第2次循环让色彩变换过度更平滑
                for (int rgb = 254; rgb >= 0 && Visible; rgb--)
                {
                    this.BackColor = Color.FromArgb(rgb, 255 - rgb, rgb);
                    Application.DoEvents();
                    System.Threading.Thread.Sleep(5);
                }
            }
        }

不加Application.DoEvents(),界面会死掉;加上的话会顺利运行。

原文地址:https://www.cnblogs.com/liuxinls/p/2909673.html