How to start a timer in a separate thread?

I have a loop as shown below

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

I want to create a timer that will check if one processing passes for more than 5 minutes. If one processing takes more than 5 minutes, it will stop the current processing and then start another processing.

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

My program is a console application.

+3
source share
4 answers

you should use System.Timers.Timer

+1
source

Take a look at ManualResetEvent and specifically WaitOne .

+3
source

Jamie asnwer System.Threading.Timer, .

+2

However, you are still unable to interrupt executable code. The code itself should provide the ability to cancel itself, which the timer could call after a certain time.

You can use the logical "shouldCancel", for example, which you check at each iteration of your loop (or even several times).

The "bad" way would be to use Thread.Abort - however this is not a very good style.

0
source

Source: https://habr.com/ru/post/1725716/


All Articles