Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3724664
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T06:43:21+00:00 2026-05-19T06:43:21+00:00

I need to delay my program’s execution for a specified number of milliseconds, but

  • 0

I need to delay my program’s execution for a specified number of milliseconds, but also want the user to be able to escape the wait when a key is pressed. If no key is pressed the program should wait for the specified number of milliseconds.

I have been using Thread.Sleep to halt the program (which in the context of my program I think is ok as the UI is set to minimise during the execution of the main method).

I have thought about doing something like this:

while(GetAsyncKeyState(System.Windows.Forms.Keys.Escape) == 0 || waitTime > totalWait)
{
    Thread.Sleep(100);
    waitTime += 100;
}

As Thread.Sleep will wait until at least the time specified before waking the thread up, there will obviously be a large unwanted extra delay as it is scaled up in the while loop.

Is there some sort of method that will sleep for a specified amount of time but only while a condition holds true? Or is the above example above the “correct” way to do it but to use a more accurate Sleep method? If so what method can I use?

Thanks in advance for your help.

Edit —- Possible Idea…

DateTime timeAtStart = DateTime.Now;
int maxWaitTime = 15000;

while (true)
{
    if (GetAsyncKeyState(System.Windows.Forms.Keys.Escape) != 0)
    {
        break;
    }

    if ((DateTime.Now - timeAtStart).TotalMilliseconds >= maxWaitTime)
    {
        break;
    }
}

This doesn’t use any sort of timer but looks like it could work, any suggestions?

Edit 2: The above works for me and now allows me to break the wait when escape is pressed. I have noticed the delay is more accurate than using Thread.Sleep too!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T06:43:23+00:00Added an answer on May 19, 2026 at 6:43 am

    First sample is using Timer, ManuelResetEvent and Global Keyboard hook:

    I did not include keyboard hook code because it’s too large. You can find it here.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    using System.Threading;
    
    namespace WindowsFormsApplication1
    {
        static class Program
        {
            private static System.Threading.Timer _timer;
            private static ManualResetEvent _signal;
    
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
    
                _signal = new ManualResetEvent(false);
    
                _timer = new System.Threading.Timer(Timer_Signaled, null, 15000, 0);
    
                _signal.WaitOne();
                _signal.Reset();
    
                Application.Run(new Form1());
            }
    
            private static void Timer_Signaled(object state)
            {
                _signal.Set();
            }
        }
    }
    

    When you hook to keyboard and ESC is pressed, simply call: _signal.Set(). This first sample is just to give you an idea.

    Second sample:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;
    
    namespace WindowsFormsApplication1
    {
        static class Program
        {
    
            [DllImport("user32.dll")]
            static extern short GetAsyncKeyState(System.Windows.Forms.Keys vKey);
    
            [STAThread]
            static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
    
                int maxWaitTime = 15000;
    
                int tc = System.Environment.TickCount;
    
                while (true)
                {
                    System.Threading.Thread.Sleep(1000);
    
                    if (System.Environment.TickCount - tc > maxWaitTime)
                    {
                        break;
                    }
    
                    if (GetAsyncKeyState(Keys.Escape) > 0)
                    {
                        break;
                    }
                }
    
                Application.Run(new Form1());
            }
        }
    }
    

    EDITED:

    First sample is more reliable as keyboard hook use callback to inform which key was pressed. Second sample works like ‘Pull’ and it can happen not every key press will be collected.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.