Alternative to Thread.Sleep in C#?

后端 未结 10 2134
半阙折子戏
半阙折子戏 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: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();
    

提交回复
热议问题