I want a program to stop executing for a certain amount of time. And i want this to happen in regular intervals. For example, i want a program to run for 5 minutes and then it should stop for 2 mintues and continue running for another 5 minutes after that. Is this possible with the C# Timer class?
You're looking for Thread.Sleep()
passing in the number of milliseconds to pause execution for.
I'm not sure this is desirable behaviour, so if you update your question you might get a better answer than this.
You can use a timer that does little more than toggle a variable (e.g. bool). If that bool is used by the application, then you can use it to control whether the application is "running".
I'm suggesting this instead of Thread.Sleep()
because at least your application is still responsive. If you want to pause a non-UI thread, then Thread.Sleep()
will suffice, but don't call Thread.Sleep()
on the UI thread, even with very short durations.
As previous answer say: what is 'stop'? The user can't use the program for 2 minutes? If so you could pop a modal dialog (with text) and the user can't close it.
If this is a Windows Forms application, you might want to consider moving this into a threaded execution model. You can do this using either the BackgroundWorker
control, thread pooling with the ThreadPool
class, asynchronous methods Begin and End (such as Stream.BeginWrite
), or by manually handling the thread yourself (bit more complex).
A BackgroundWorker
will provide the easiest form of development by allowing you to handle events for the asynchronous code, and update a progress bar or label to show the current state of the execution. This will allow you to use Thread.Sleep
without the system warning the user that the application has hung.
Basically, in Windows Forms development you should be using some form of threading to handle long executions.