Alternative to Thread.Sleep in C#?

后端 未结 10 2001
半阙折子戏
半阙折子戏 2020-12-19 07:10

I have a code which when run, it executes series of lines in sequence. I would like to add a pause in between.

Currently, I have it like this

//do wo         


        
相关标签:
10条回答
  • 2020-12-19 07:29

    Your problem is that you're blocking the main thread of your application, which is responsible for keeping the ui running. You shouldn't do this. Instead use a timer - the Forms one is probably easiest in a Forms app, or consider BackgroundWorker. (For such a long wait a timer is probably more suitable)

    0 讨论(0)
  • 2020-12-19 07:29

    Have a look Thread.Sleep(300) not working correctly

    Probably you need to use the "Dispatcher". Have a look here as well

    0 讨论(0)
  • 2020-12-19 07:40

    Please see this MSDN reference on the System.Threading.Timer class. There is a great explanation, all of the class members, and some sample code for you to follow when testing/learning.

    Mind you, though, the Timer should be used when you want to fire an event at a certain interval. If you are just looking to pause execution of your application, then you should go with Thread.Sleep(). However, as many others have pointed out, you are causing your thread to sleep for an extended amount of time.

    0 讨论(0)
  • 2020-12-19 07:41

    Your software would freeze if that sleep is on the main thread. Keep in mind the parameter is in milliseconds. 10 800 000 milliseconds = 10 800 seconds

    Another way to pass the time is to pass a TimeSpan object instead. Ex:

    // Sleep for 10 seconds
    System.Threading.Thread.Sleep(new TimeSpan(0, 0, 10));
    

    As for timer:

    You can use System.Timers.Timer;

    Timer timer = new Timer();
    timer.Interval = 20; // milliseconds
    timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
    timer.AutoReset = true; // if not set you will need to call start after every event fired in the elapsed callback
    timer.Start();
    
    0 讨论(0)
  • 2020-12-19 07:43

    USE A TIMER!

    private DispatcherTimer Timer;
    public Constructor
    {
        Timer = new System.Windows.Threading.DispatcherTimer();
        Timer.Tick += new EventHandler(Timer_Tick);
        Timer.Interval = new TimeSpan(0,0,10);
        Timer.Start();
    }
    
    
    private void Timer_Tick(object sender, EventArgs e)
    {
        Timer.Stop();
        Timer -= Timer_Tick;
        Timer = null;
        // DO SOMETHING
    }
    
    0 讨论(0)
  • 2020-12-19 07:45

    You're sleeping the thread for 10800 seconds, or 3 hours. Thread.Sleep() is designed to freeze your thread, stop anything from working in the software for that duration. In this case, the duration is 18 minutes. What are you trying to do?

    0 讨论(0)
提交回复
热议问题