Scaraffe
Scaraffe

Reputation: 5241

Using C# Timer to stop executing a Program

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?

Upvotes: 0

Views: 1619

Answers (5)

mughis
mughis

Reputation: 21

You can use Window.Forms.Timer to register a callback each 1000ms

        private int counter;
        void StartTimer()
        {
            counter = 0;
            Timer timer = new Timer();
            timer.Interval = 1000;
            timer.Enabled = true;
            timer.Tick += Timer_Tick;
        }

In the event function simply increment a global counter variable that executes when a condition fulfills


        private void Timer_Tick(object sender, EventArgs e)
        {
            counter++;
        }

Upvotes: 0

Codesleuth
Codesleuth

Reputation: 10541

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.

Upvotes: 0

Neil Barnwell
Neil Barnwell

Reputation: 42165

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.

Upvotes: 1

RvdK
RvdK

Reputation: 19800

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.

Upvotes: 0

Agent_9191
Agent_9191

Reputation: 7253

You're looking for Thread.Sleep() passing in the number of milliseconds to pause execution for.

Upvotes: 3

Related Questions