1. ホーム

C# 遅延プログラム遅延

2022-02-08 03:40:01
Sleep(), there are too many disadvantages, so I won't talk about it. Use While (1) this consumes system resources card can not, so the use of events blocking is the best. But blocking UI will be stuck to create a new thread of their own.
1. Create a new thread for functions that require a delay, or the UI will definitely get stuck.
2. Use AutoResetEven to block threads.
3, then use the system (must be the system) timer, to time the thread, and finally depart to turn on blocking.
4. Finally dispose timer, this timer resets old friends

        AutoResetEvent MyDelayEvent = new AutoResetEvent(false); //define event 
        public void myDealyTime(int time)
        {
            Timers MyDelayTimer = new System.Timers.Timer(time); //set timer
            //call the delay function to set and start the delay timer, then wait.
            //MyDelayTimer.Interval = time;
            MyDelayTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            MyDelayTimer.AutoReset = true; //Every time Elapsed event is triggered once (false), or always triggered (true), to use true will reset the time.
            MyDelayTimer.Enabled = true; //Whether to trigger the Elapsed event
            MyDelayTimer.Start();
            MyDelayEvent.WaitOne();
            MyDelayTimer.Dispose();
            Console.WriteLine("aa");

        }

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




First time blogger, please reply more often.

3, then use the system (must be the system) timer, to time the thread, and finally depart to turn on blocking.

4. Finally dispose timer, this timer resets old friends

        AutoResetEvent MyDelayEvent = new AutoResetEvent(false); //define event 
        public void myDealyTime(int time)
        {
            Timers MyDelayTimer = new System.Timers.Timer(time); //set timer
            //call the delay function to set and start the delay timer, then wait.
            //MyDelayTimer.Interval = time;
            MyDelayTimer.Elapsed += new System.Timers.ElapsedEventHandler(Timer_TimesUp);
            MyDelayTimer.AutoReset = true; //Every time Elapsed event is triggered once (false), or always triggered (true), to use true will reset the time.
            MyDelayTimer.Enabled = true; //Whether to trigger the Elapsed event
            MyDelayTimer.Start();
            MyDelayEvent.WaitOne();
            MyDelayTimer.Dispose();
            Console.WriteLine("aa");

        }

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



First time blogger, please reply more often.