[Winform Study Notes (9)] Winform form program delay function

Winform form program delay function

Preface

When developing a Winform form program, sometimes it is necessary for the program to delay or sleep for a few seconds. If the Thread.Sleep() method is used directly, it will cause the program to suspended animation and the UI interface to stop responding. This article mainly introduces a method to prevent the program from suspended animation
. Other messages can also be responded to during the delay process.

text

1. Specific code

/// <summary>
/// 延迟函数(毫秒级)
/// </summary>
/// <param name="time">需要延迟的时间</param>
public static void Delay(double time)
{
    
    
    double strart = Environment.TickCount;
    while (Math.Abs(Environment.TickCount - strart) < time)
    {
    
    
        Application.DoEvents();
    }
}

2. Usage examples

  1. Use the Delay() method

            public void Add(int a,int b)
            {
          
          
                Delay(5000);
                label1.Text = (a + b).ToString();
            }
    

    Insert image description here
    As you can see from the above animation, after executing the main form method, you can also perform other operations.

  2. Use the Thread.Sleep() method

            public void Add(int a,int b)
            {
          
          
                Thread.Sleep(5000);
                label1.Text = (a + b).ToString();
            }
    

    Insert image description here
    You can see from the animation that when the main form method is executed, the UI interface stops responding, and the subform pops up after the delay time expires.

Guess you like

Origin blog.csdn.net/sallyyellow/article/details/132476560