Alternative to Thread.Sleep in C#?

后端 未结 10 2112
半阙折子戏
半阙折子戏 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:49

    The Thread.Sleep is what you want to use for this, you may want to use a more reasonable sleep period than 3 hours though.

    Update:

    After reading some of the comments, Thread.Sleep is probably not what you want. Use a System.Threading.Timer instead as others have suggested.

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

    You can replace

    Thread.Sleep(X);
    

    by

    Task.WaitAll(Task.Delay(X));
    
    0 讨论(0)
  • 2020-12-19 07:55

    Thread.Sleep would typically be used to pause a separate thread, not in the main thread of your app.

    Timer would typically be used to periodically cause the main thread to stop its normal operations and handle an event.

    Either method can be used to periodically perform a function after a certain time interval.

    What I wouldn't do is ask the main thread to sleep for 3 hours.

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

    I think you should use a Monitor. It helps you to put a wait on objects and release the lock when you need to continue running the program.

    You should find your answer here: Safe Thread Synchronization

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