none
How to make a delay using c#? For example make a program wait ? RRS feed

  • Question

  • My question is how to make a program wait for example 1 sec without Thread.Sleep();, i dont want Thread.Sleep because it like stops and the user of the program will think it crashed. Any ideas?
    Friday, May 3, 2019 7:50 PM

Answers

  • Hi   Stefan Nachov,

    Thank you for posting here.

    From your description, I have made a sample on my side, and I use the following methods to make a ‘delay’ using c#.

    Method 1:    

    Use the “Interval” property of System.Timers.Timer to set the interval.

    The following code will execute “OnTimedEvent” in five seconds:

         private static Timer aTimer;
    
            static void Main(string[] args)
            {
                aTimer = new System.Timers.Timer();
                aTimer.Interval = 5000;
                // Hook up the Elapsed event for the timer. 
                aTimer.Elapsed += OnTimedEvent;
                // Start the timer
                aTimer.Enabled = true;
                Console.ReadKey();
            }
    
            private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
            {
                //code
                Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
                aTimer.Enabled = false;
         aTimer.Dispose();
                       }

    Method 2:

    The following method is to use a function “Wait” to block execution of the current thread during the “ms” milliseconds,

    You can use the thread to execute the delay function avoid the main thread blocking. 

       public static void Wait(object ms)
            {
                var timeout = DateTime.Now.AddMilliseconds(Convert.ToDouble(ms));
                Console.WriteLine("Second thread is executing");
                while (true)
                {
                    if (DateTime.Now > timeout)
                    {
                        Console.WriteLine("Second thread is finished");
                        break;
                    }
                }        }
            
            static void Main(string[] args)
            {
                Thread myThread = new Thread(new ParameterizedThreadStart(Wait));
                myThread.Start(5000);
                Console.WriteLine("Main Thread executes normally");
                // code in the main Thread.
                Console.ReadKey();
            }

    Hope these solutions can help you.


    Best Regards

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, May 6, 2019 5:37 AM
    Moderator
  • I suspect you aren't asking the right question.  If you want the program to wait, then you use Thread.Sleep().  That's what it's for.  If you sleep too long, Windows will mark the GUI as "(Not responding)", because you told it to wait.

    I suspect what you really want to know is "how can I start some action 1 second from now while keeping the GUI active?"  That's not waiting.  To do that, you use System.Windows.Forms.Timer and add an EventHandler to its Tick event.  The handler will be called when the timer expires.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Saturday, May 4, 2019 12:00 AM
  • Or do you want your program/task wait for a second, while the UI of your app still remains responsive?  Then you might think about dividing the workload by using a BackgroundWorker or Task.Run, depending on the platform you're using (Winforms, WPF, etc.?).

    wizend

    Saturday, May 4, 2019 11:33 AM

All replies

  • I fail to see why thread.sleep for 1 second will make someone think a program crashed?  
    Friday, May 3, 2019 9:04 PM
  • I suspect you aren't asking the right question.  If you want the program to wait, then you use Thread.Sleep().  That's what it's for.  If you sleep too long, Windows will mark the GUI as "(Not responding)", because you told it to wait.

    I suspect what you really want to know is "how can I start some action 1 second from now while keeping the GUI active?"  That's not waiting.  To do that, you use System.Windows.Forms.Timer and add an EventHandler to its Tick event.  The handler will be called when the timer expires.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Saturday, May 4, 2019 12:00 AM
  • Or do you want your program/task wait for a second, while the UI of your app still remains responsive?  Then you might think about dividing the workload by using a BackgroundWorker or Task.Run, depending on the platform you're using (Winforms, WPF, etc.?).

    wizend

    Saturday, May 4, 2019 11:33 AM
  • Hi   Stefan Nachov,

    Thank you for posting here.

    From your description, I have made a sample on my side, and I use the following methods to make a ‘delay’ using c#.

    Method 1:    

    Use the “Interval” property of System.Timers.Timer to set the interval.

    The following code will execute “OnTimedEvent” in five seconds:

         private static Timer aTimer;
    
            static void Main(string[] args)
            {
                aTimer = new System.Timers.Timer();
                aTimer.Interval = 5000;
                // Hook up the Elapsed event for the timer. 
                aTimer.Elapsed += OnTimedEvent;
                // Start the timer
                aTimer.Enabled = true;
                Console.ReadKey();
            }
    
            private static void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
            {
                //code
                Console.WriteLine("The Elapsed event was raised at {0:HH:mm:ss.fff}",
                          e.SignalTime);
                aTimer.Enabled = false;
         aTimer.Dispose();
                       }

    Method 2:

    The following method is to use a function “Wait” to block execution of the current thread during the “ms” milliseconds,

    You can use the thread to execute the delay function avoid the main thread blocking. 

       public static void Wait(object ms)
            {
                var timeout = DateTime.Now.AddMilliseconds(Convert.ToDouble(ms));
                Console.WriteLine("Second thread is executing");
                while (true)
                {
                    if (DateTime.Now > timeout)
                    {
                        Console.WriteLine("Second thread is finished");
                        break;
                    }
                }        }
            
            static void Main(string[] args)
            {
                Thread myThread = new Thread(new ParameterizedThreadStart(Wait));
                myThread.Start(5000);
                Console.WriteLine("Main Thread executes normally");
                // code in the main Thread.
                Console.ReadKey();
            }

    Hope these solutions can help you.


    Best Regards

    Yong Lu


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, May 6, 2019 5:37 AM
    Moderator