C# 占用系统资源少的延时

转发自:https://www.csdn.net/gather_24/MtTaUg3sMDg4LWJsb2cO0O0O.html

不用Thread.Sleep(),缺点太多,我就不说了。 采用While(1)这个耗费系统资源卡的不行,所以用事件的阻塞是最好的。但阻塞UI会卡就要自己新建一个线程。
1、适用新建线程来做有延迟需求的函数,要不然UI一定会卡。
2、用AutoResetEven来阻塞线程,
3、然后用系统(一定是系统)定时器,来计时,最后出发打开阻塞。
4、最后dispose定时器,这个定时器复位老友
        AutoResetEvent MyDelayEvent = new AutoResetEvent(false);            //定义事件 
        public  void myDealyTime(int time)
        {
            System.Timers.Timer MyDelayTimer = new System.Timers.Timer(time);   //设置定时器
            //调用延迟函数,设置和启动延时定时器,然后等待。
            //MyDelayTimer.Interval = time;
            MyDelayTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            MyDelayTimer.AutoReset = true; //每到指定时间Elapsed事件是触发一次(false),还是一直触发(true),要用true会复位时间。
            MyDelayTimer.Enabled = true; //是否触发Elapsed事件
            MyDelayTimer.Start();
            MyDelayEvent.WaitOne();
            MyDelayTimer.Dispose();
            Console.WriteLine("aa");

        }

        private void Timer_TimesUp(object sender, System.Timers.ElapsedEventArgs e)
        {
           
            MyDelayEvent.Set();
            Console.WriteLine("bb");
        }


System.Windows.Formsusing
System;using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace ConsoleApp2
{   
 public class Timer   
 {       
  public delegate void TimerCompleteDelegate();
          [DllImport("kernel32.dll")]       
  static extern IntPtr CreateWaitableTimer(IntPtr lpTimerAttributes, bool bManualReset, string lpTimerName);
          [DllImport("kernel32.dll")]       
  static extern bool SetWaitableTimer(IntPtr hTimer, [In] ref long ft, int lPeriod, TimerCompleteDelegate pfnCompletionRoutine, IntPtr pArgToCompletionRoutine, bool fResume);           [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Auto)]      
   [return: MarshalAs(UnmanagedType.Bool)]      
   static extern bool CloseHandle(IntPtr hObject);        
  [DllImport("User32.dll")]      
   static extern int MsgWaitForMultipleObjects(int nCount, ref IntPtr handle, bool fWaitAll, int dwMilliseconds, int dwWakeMask);         
  /// <summary>       
  /// 不占用cpu,窗口不卡死,不影响其它代码执行       
  /// </summary>      
   /// <param name="time">单位毫秒</param>       
  public static bool Sleep(int time)       
  {       
   TimerCompleteDelegate TimerComplete = new TimerCompleteDelegate(TimerCompleted);
                   long Interval = -10 * time * 1000;//占8字节
                   //创建计时器
              IntPtr handle =CreateWaitableTimer(IntPtr.Zero, true, "WaitableTimer");
                 SetWaitableTimer(handle, ref Interval, 0, TimerComplete, IntPtr.Zero, true);
                  //等待消息抵达
                 while (MsgWaitForMultipleObjects(1, ref handle, false, -1, 255) != 0)
                 {               
   //转让权限               
   Application.DoEvents();
                 }
                 return CloseHandle(handle);


           }
         private static void TimerCompleted()
         {           
   // 一旦定时器过期,就执行例程。这是独立于调用OnTimeRebug事件的类实现的程序执行的。       
  } 
 
 }

}
————————————————
版权声明:本文为CSDN博主「绯樱」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq1031622947/article/details/80210702

原文地址:https://www.cnblogs.com/2SBC/p/12898576.html