Starting and stopping the method in one minute

timer1= new System.Windows.Forms.Timer(); timer1.Interval =60000; // 1 min timer1.Start(); MyMethodName(); timer1.Stop(); 

MyMethodName ()

- has a for loop for 90,000 entries (and some checks inside this loop).

 for (int i = 0; i <= 90000; i++) { //validations go here } 

When the time in timer 1 runs for a minute, I want to stop other entries in the for loop. For example, if 45,000 records are executed in a minute, I want to stop the ie method. stop the method after a minute.

However, the above timer code is executed until all 90000 entries are completed in a for loop, somehow the method does not start for a minute? Any help?

+4
source share
6 answers

Two things. Firstly, your timer code is not actually related to running MyMethodName . The timer is designed to start processes after a period of time (and possibly at regular intervals, depending on how it is configured.

Secondly, in more detail about your question, in order to break the loop, you have to put the code inside the loop. The key should be to have a stopwatch or similar start before your cycle, and then at the beginning of the cycle check how much time has passed. If it is a minute or more, then break; .

The main thing to note is that you will not stop for exactly a minute, but you will end with an iteration of a loop that works when the minute expires and then stops. This is usually what you want, as stopping processing halfway through something can cause unpleasant side effects.

 Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); for (int i =0; i<=90000; i++) { if (stopwatch.Elapsed>TimeSpan.FromSeconds(5)) break; Console.WriteLine(i); Thread.Sleep(1000); } 

Please note that Thread.Sleep exists only because otherwise I will go through all 90,000 iterations too quickly .; -)

+2
source

So you probably need a significantly different implementation. Consider this:

 public class MyForm { private BackgroundWorker _worker; public MyForm() { _worker = new BackgroundWorker(); _worker.DoWork += (s, args) => { var timer = Stopwatch().StartNew(); do { // do something } while (timer.ElapsedMilliseconds < 60000) }; } } 

and then when you want to run it:

 _worker.RunWorkerAsync(); 

However, you can make it even more reliable. You can pass the time as follows:

 _worker.RunWorkerAsync(60000); 

and then in the DoWork handler do the following:

 while (timer.ElapsedMilliseconds < (int)args.Argument) 

In addition, with BackgroundWorker you can support undo. Just set the WorkerSupportsCancellation flag to true , and then able to do the following:

 while (timer.ElapsedMilliseconds < (int)args.Argument && !_worker.CancellationPending) 

therefore, if necessary, you can do this:

 _worker.CancelAsync(); 
+2
source

Hmm, use a stopwatch instead

  Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); for(int i= 0; i <= 90000; i++) { // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; if(ts.Seconds >= 60) break; } 
+1
source

However, the above timer code is executed until all 90000 entries are completed in a for loop, somehow the method does not start for a minute? Any help?

The timer will not generate events until you release the user interface thread, which will not execute until the method completes completely.

If you want the method to not run for a certain duration, you can access it directly in your method:

 MyMethodName(TimeSpan.FromMinutes(1)); 

Then in your method:

 void MyMethodName(TimeSpan maxRuntime) { DateTime expiration = DateTime.Now + maxRuntime; for (int i = 0; i <= 90000; i++) { //validations go here if (i % 100 == 0) // check every 100? { if (DateTime.Now > expiration) break; } } } 

So the best approach would be to push it into the background thread and discard it as needed.

+1
source

you can set a flag in the validation to see if this is done or not by attaching an event handler to the Tick event in the Timer object

 //in an area accessible to //both elements object readonly _lock = new object(); bool elapsed = false; 

where was your source code

 elapsed = false; timer1= new System.Windows.Forms.Timer(); timer1.Interval =60000; // 1 min timer1.Tick=((sender, everntArgs)=> { lock(_lock) elapsed = true; }); timer1.Start(); MyMethodName(); timer1.Stop(); 

Inside MyMethodName

 //inside the loop for (int i = 0; i <= 90000; i++) { //validations go here lock(_lock) if(elapsed) break; } 
0
source

If you use a CancellationTokenSource with the CancellationTokenSource(TimeSpan) constructor, it makes it easier to write a method that cancels the action after the specified time.

You can write a method like this:

 public static void RunTimedAction(Action<CancellationToken> action, TimeSpan timeout) { using (var cancellationTokenSource = new CancellationTokenSource(timeout)) action(cancellationTokenSource.Token); } 

And then you can write any action that takes a CancellationToken as a parameter, for example:

 private void action(CancellationToken cancel) { int i; for (i = 0; i < 1000000; ++i) { if (cancel.IsCancellationRequested) break; Thread.Sleep(10); // Simulate work. } Console.WriteLine("action() reached " + i); } 

What you can use as follows:

 Console.WriteLine("Started at " + DateTime.Now); RunTimedAction(action, TimeSpan.FromSeconds(10)); Console.WriteLine("Stopped at " + DateTime.Now); 

Combine this into a complete demo program:

 using System; using System.Threading; namespace Demo { class Program { void run() { Console.WriteLine("Started at " + DateTime.Now); RunTimedAction(action, TimeSpan.FromSeconds(10)); Console.WriteLine("Stopped at " + DateTime.Now); } private void action(CancellationToken cancel) { int i; for (i = 0; i < 1000000; ++i) { if (cancel.IsCancellationRequested) break; Thread.Sleep(10); // Simulate work. } Console.WriteLine("action() reached " + i); } public static void RunTimedAction(Action<CancellationToken> action, TimeSpan timeout) { using (var cancellationTokenSource = new CancellationTokenSource(timeout)) action(cancellationTokenSource.Token); } static void Main() { new Program().run(); } } } 
0
source

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


All Articles