views:

134

answers:

4

I have a loop like below

for(int i = 0; i < 10; i++)
{
    // some long time processing
}

I want to create a timer, which would check if one processing runs more than 5 minutes. If one processing runs more than 5 minutes, it would stop current processing then start another processing.

Is it possible to make another thread to monitor the main loop?

My program is a console application.

+2  A: 

Take a look at ManualResetEvent and specifically the WaitOne method.

Jamiec
+1  A: 

you should use System.Timers.Timer

Fredou
Actually it's `System.Timers.Timer`
Alex Bagnolini
what is the different between the System.Timers.timer and System.Threading.Timer
Yongwei Xing
@Alex, fixed (15chars)
Fredou
System.Timers.Timer is the IComponent (designer drag-drop) version of System.Threading.Timer - http://mark.michaelis.net/Blog/SystemWindowsFormsTimerVsSystemThreadingTimerVsSystemTimersTimer.aspx
Richard Szalay
In my situation,which one is the correct one?
Yongwei Xing
@Richard, no that is form.timers
Fredou
@Yongwei, I would say the timers.timer one but I might be wrong
Fredou
@Fredou, I think you are right, I did a simple test. It's great.
Yongwei Xing
@Fredou, no Form.Timers runs on the UI thread. System.Timers.Timer extends Component and thus is available for drag-drop.
Richard Szalay
@richard, I might be wrong but I think that forms.timer will wait if the UI hang, not the system.timers.timer
Fredou
Timers.Timer and Threading.Timer both run on a separate thread (not the UI thread). However, Timers.Timer extends Component so is still available for drag-drop in the design time environment.
Richard Szalay
@richard, I just tried with form.timers and it ignore the UI thread if it hang. my mistake
Fredou
i'm currently looking at both in reflector to see how they work
Fredou
An explanation of the different timer types: http://msdn.microsoft.com/en-us/magazine/cc164015.aspx
Oliver
+1  A: 

In addition to Jamie's asnwer you can use the System.Threading.Timer, which will execute in a background thread.

Richard Szalay
A: 

However, you are still not really able to abort the running code. The code iteself has to provide an ability to cancel itself which the timer could invoke after a certain time.

You could use a boolean "shouldCancel" for example which you are checking in every iteration of your loop (or even multiple times).

The "bad" way would be using Thread.Abort - however, this is not really good style.

winSharp93