none
C# wait for x seconds

Answers

  • System.Threading.Thread.Sleep(5000);

    this codes make your application waiting for 5 seconds

    Sunday, February 26, 2006 10:15 AM
  • Yes, Thread.Sleep will stop the executing thread for given amount of time. However if you want remain responsive (UI doesn't freeze) you might consider timers.
    Sunday, February 26, 2006 11:03 AM
  • Hi

    You have Suuspended the execution of the same thread where the UI is also loading .... So you have to perform the action in a seperate Thread to be responsive on the User Interface.

    Monday, February 27, 2006 1:29 PM
  • timer or sleep. if you want to perform some tasks after a certain time and use timer, set the interval as the time to wait, and enable it when needed. If it is needed once only, disable the timer in the timer tasks.
    Monday, February 27, 2006 1:29 AM

All replies

  • You can make use of a timer, you can set the time in miliseconds
    • Proposed as answer by ta_gr Tuesday, March 12, 2013 9:00 AM
    Sunday, February 26, 2006 9:23 AM
  • System.Threading.Thread.Sleep(5000);

    this codes make your application waiting for 5 seconds

    Sunday, February 26, 2006 10:15 AM
  • Yes, Thread.Sleep will stop the executing thread for given amount of time. However if you want remain responsive (UI doesn't freeze) you might consider timers.
    Sunday, February 26, 2006 11:03 AM
  • timer or sleep. if you want to perform some tasks after a certain time and use timer, set the interval as the time to wait, and enable it when needed. If it is needed once only, disable the timer in the timer tasks.
    Monday, February 27, 2006 1:29 AM
  • Hi

    You have Suuspended the execution of the same thread where the UI is also loading .... So you have to perform the action in a seperate Thread to be responsive on the User Interface.

    Monday, February 27, 2006 1:29 PM
  • System.Threading.Thread.Sleep(5000);

     

    Monday, October 08, 2007 12:03 PM
  • Remark before you continue reading: I just learned C# and programming a couple of months ago and I am certainly not a C# Pro, so I guess there are better ways to solve the problem.However, I thought, I just post how I solved the problem, maybe it helps someone out there.

    When I first developed my app, I didn't think about a waiting function, but at the end I needed to implement it because of functional reasons. My app does very lengthy operations that can take up to 6 hours or more.

    First, I used System.Threading.Thread.Sleep(), which is probably the easiest way to implement a wait function. But my app crashed always after approx. 20 minutes due to an OutOfMemoryException. Then I started diving into the C# garbage collectors and C#destructors to check if I can decrease the memory usage of my app. I partly succeeded (especially with GC.Collect()), but  I won only some minutes.

    Then, I tried to implement System.Timers.Timer(), but I had problems to modify my app's classes& methods accordingly. Maybe, it would not have been that hard to implement it, if I had know right from the beginning of my project that I needed to implement a wait function and maybe it's now also still easy to implement, but I just don't know how to do it.

    So, at the end I chose the "medieval ages" solution, which is not very elegant, but it does exactly what I want it to do:

    ....waits for a specified amount of time

    ...does not consume memory resources like Thread.Sleep()

    ...can be easily pasted in every sequence, just where I need it without effecting the existing code.

    Here it is:

          Stopwatch sw = new Stopwatch(); // sw cotructor
          sw.Start(); // starts the stopwatch
          for (int i = 0; ; i++) 
          {
            if (i % 100000 == 0) // if in 100000th iteration (could be any other large number
            // depending on how often you want the time to be checked) 
            {
              sw.Stop(); // stop the time measurement
              if (sw.ElapsedMilliseconds > 5000) // check if desired period of time has elapsed
              {
                break; // if more than 5000 milliseconds have passed, stop looping and return
                // to the existing code
              }
              else
              {
                sw.Start(); // if less than 5000 milliseconds have elapsed, continue looping
                // and resume time measurement
              }
            }
          }

    • Edited by Booler84 Saturday, October 02, 2010 6:48 PM formatting
    Saturday, October 02, 2010 6:39 PM
  • Thanks you for this tips
    Uiop
    • Proposed as answer by ManFuchs Tuesday, February 12, 2013 2:03 PM
    Monday, January 16, 2012 2:36 PM
  • While its great that this doesn't use as much memory resources I think you'll find running any repetitive loop like this will consume 20 - 30 percent of your CPU time for the extent of the process.
    Thursday, January 24, 2013 8:24 PM
  • To wait for x seconds in C# easiest way is to use this:

    System.Threading.Thread.Sleep(x000);//where x is the time in seconds for which you want app to wait

    Example:

    System.Threading.Thread.Sleep(4000);//will wait for 4 seconds

    For more detailed explanation and more informative stuff about delay,wait and threads visit

    http://codesmesh.com/c-sleep-function-to-give-delay/

    Thursday, April 04, 2013 8:11 PM
  • something like this is easy to understand and it doesn't cause your app to wait(single threaded) and you get to control and see what is going on.

                    DateTime Tthen = DateTime.Now;
                    do
                    {
                        Application.DoEvents();
                    } while (Tthen.AddSeconds(5) > DateTime.Now);      

    //Waits 5 seconds.


    geek

    Wednesday, December 04, 2013 8:11 PM
  • I am using the following ExtensionMethod to delay execute code.
    
    
        namespace Core.Extensions
        {
        using System;
        using System.Collections.Generic;
        using System.Windows.Threading;
    
        public static class DelayedExecutionExtension
        {
            #region Static Fields
    
            private static readonly Dictionary<object, DispatcherTimer> _elementDictionary = new Dictionary<object, DispatcherTimer>();
    
            private static readonly Dictionary<object, List<DispatcherTimer>> _elementDictionaryList =
                new Dictionary<object, List<DispatcherTimer>>();
    
            #endregion
    
            #region Public Methods
    
            public static void DelayedExecute(this object scroll, Action method)
            {
                DelayedExecute(scroll, 100, method);
            }
    
            public static void DelayedExecute(this object scroll, int milliseconds, Action method)
            {
                lock (_elementDictionary)
                {
                    if (_elementDictionary.ContainsKey(scroll))
                    {
                        _elementDictionary[scroll].Stop();
                        _elementDictionary[scroll] = CreateNewTimer(method, scroll, milliseconds);
                    }
                    else
                        _elementDictionary.Add(scroll, CreateNewTimer(method, scroll, milliseconds));
                }
            }
    
            public static void DelayedExecuteEnqueue(this object scroll, Action method)
            {
                DelayedExecuteEnqueue(scroll, 100, method);
            }
    
            public static void DelayedExecuteEnqueue(this object scroll, int milliseconds, Action method)
            {
                lock (_elementDictionary)
                {
                    lock (_elementDictionaryList)
                    {
                        if (_elementDictionary.ContainsKey(scroll))
                        {
                            if (_elementDictionaryList.ContainsKey(scroll))
                            {
                                AddNewTimer(scroll, milliseconds, method);
                                return;
                            }
                            lock (_elementDictionary)
                                _elementDictionaryList.Add(
                                    scroll,
                                    new List<DispatcherTimer>
                                    {
                                        _elementDictionary[scroll]
                                    });
                            AddNewTimer(scroll, milliseconds, method);
                            return;
                        }
                    }
                }
                DelayedExecute(scroll, milliseconds, method);
            }
    
            public static void RemoveDelayedExecute(this object scroll)
            {
                lock (_elementDictionary)
                {
                    DispatcherTimer local0;
                    if (_elementDictionary.TryGetValue(scroll, out local0))
                    {
                        local0.Stop();
                        _elementDictionary.Remove(scroll);
                    }
                }
                RemoveDelayedExecuteQueue(scroll);
            }
    
            #endregion
    
            #region Methods
    
            private static void AddNewTimer(object scroll, int milliseconds, Action method)
            {
                var newTimer = CreateNewTimer(method, scroll, milliseconds);
                lock (_elementDictionaryList)
                    _elementDictionaryList[scroll].Add(newTimer);
            }
    
            private static DispatcherTimer CreateNewTimer(Action method, object elem, int milliseconds)
            {
                var timer = new DispatcherTimer
                            {
                                Interval = TimeSpan.FromMilliseconds(milliseconds)
                            };
                timer.Tick += (EventHandler)((d, e) =>
                {
                    method();
                    timer.Stop();
                    lock (_elementDictionary)
                        _elementDictionary.Remove(elem);
                    lock (_elementDictionaryList)
                    {
                        if (!_elementDictionaryList.ContainsKey(elem))
                            return;
                        _elementDictionaryList[elem].Remove(timer);
                        if (_elementDictionaryList[elem].Count != 0)
                            return;
                        _elementDictionaryList.Remove(elem);
                    }
                });
                timer.Start();
                return timer;
            }
    
            private static void RemoveDelayedExecuteQueue(object scroll)
            {
                lock (_elementDictionaryList)
                {
                    List<DispatcherTimer> local0;
                    if (!_elementDictionaryList.TryGetValue(scroll, out local0))
                        return;
                    foreach (var item0 in local0)
                        item0.Stop();
                    _elementDictionaryList.Remove(scroll);
                }
            }
    
            #endregion
        }
    }
    
    if you want to delay an execution and reset the timer if another request araises in this time, very useful if you have an event that is fired many times, but you want to wait for a timespan and execute only once.. use
    
        this.DelayExecute(500,() => MyDelayedMethodCall());
    
    or if you want to enque and execute all calls use:
    
        this.DelayExecuteEnqueue(500,() => MyDelayedMethodCall());
    
    
    
    

    
    Tuesday, December 16, 2014 2:13 PM