SoFunction
Updated on 2025-03-06

Instructions for using C# delay function

C# delay function use

If delay is required in threads, try not to use the Sleep() function, as this will cause the time slice to be cut into other threads.

Use the following functions:

    //Delay function
    public static void Delay(int milliSecond)
    {
        int start = ;
        while (( - start) < milliSecond)
        {
            ();
         }
    }

or:

        //Delay us   Create a waitable timer
        [DllImport("")]
        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, , 
                    QS_TIMER)) ;
            CloseHandle(hWaitTimer);
        }

C# 3 delay functions

public static void Delays(int DelayTime = 100)
        {
            int time = ;
            while (true)
            {
                if ( - time &gt;= DelayTime)
                {
                    break;
                }
                ();
                (10);
            }
        }
 
        public static void Delay1(int milliSecond)
        {
            int start = ;
            while (( - start) &lt; milliSecond)
            {
                ();
            }
        }
 
        //Delay program seconds        public static bool Delay2(int delayTime)
        {
            DateTime now = ;
            int s;
            do
            {
                TimeSpan spand =  - now;
                s = ;
                ();
            }
            while (s &lt; delayTime);
            return true;
        }

The above is personal experience. I hope you can give you a reference and I hope you can support me more.