软件编程
位置:首页>> 软件编程>> C#编程>> C#延时函数的使用说明

C#延时函数的使用说明

作者:海歌也疯狂  发布时间:2023-10-11 19:58:34 

标签:C#,延时,函数

C#延时函数使用

在线程中如果需要延时,尽量不要使用Sleep()函数,这样会导致时间片切到别的线程中。

使用如下函数: 

    //Delay function
    public static void Delay(int milliSecond)
    {
        int start = Environment.TickCount;
        while (Math.Abs(Environment.TickCount - start) < milliSecond)
        {
            Application.DoEvents();
         }
    }

或者:

        //Delay us   Create a waitable timer
        [DllImport("kernel32.dll")]
        public static extern int CreateWaitableTimer(int lpTimerAttributes,
                                     bool bManualReset, int lpTimerName);
 
        public static void UsDelay(int us)
        {
            long duetime = -10 * us;
            int hWaitTimer = CreateWaitableTimer(NULL, true, NULL);
            SetWaitableTimer(hWaitTimer, ref duetime, 0, NULL, NULL, false);
            while (MsgWaitForMultipleObjects(1, ref hWaitTimer, false, Timeout.Infinite, 
                    QS_TIMER)) ;
            CloseHandle(hWaitTimer);
        }

C#3个延时函数 

public static void Delays(int DelayTime = 100)
       {
           int time = Environment.TickCount;
           while (true)
           {
               if (Environment.TickCount - time >= DelayTime)
               {
                   break;
               }
               Application.DoEvents();
               Thread.Sleep(10);
           }
       }

public static void Delay1(int milliSecond)
       {
           int start = Environment.TickCount;
           while (Math.Abs(Environment.TickCount - start) < milliSecond)
           {
               Application.DoEvents();
           }
       }

//延时程序 秒
       public static bool Delay2(int delayTime)
       {
           DateTime now = DateTime.Now;
           int s;
           do
           {
               TimeSpan spand = DateTime.Now - now;
               s = spand.Seconds;
               Application.DoEvents();
           }
           while (s < delayTime);
           return true;
       }

来源:https://blog.csdn.net/qq_31094099/article/details/80461035

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com