运行和停止方法一分钟 [英] Run and stop a method for a minute

查看:54
本文介绍了运行和停止方法一分钟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

MyMethodName()

MyMethodName()

-有一个90,000个条目的for循环(以及for循环中的一些验证).

-has a for loop for 90,000 entries (and some validations inside that for loop).

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

}

当timer1中的时间结束一分钟后,我想停止执行for循环中的其他条目.例如,如果在一分钟内完成45,000个条目,我想停止执行该方法,即.一分钟后停止该方法.

When the time in timer1 is done for a minute, i want to stop executing other entries in the for loop. For example, if 45,000 entries are done in a minute, i want to stop executing the method ie. stop the method after a minute.

但是上面的计时器代码要执行直到90000条记录都在for循环内循环执行,而该方法一分钟不能运行?有帮助吗?

However the above timer code, executes till all the 90000 records are done looping inside the for loop, somehow the method doesn't run for a minute? Any help?

推荐答案

两件事.首先,您的计时器代码实际上未与 MyMethodName 的运行相关.计时器设计为在经过时间后运行进程(并可能以固定的时间间隔,具体取决于设置时间).

Two things. Firstly Your timer code is not actually connected to the running of MyMethodName. A timer is designed to run processes when the time has elapsed (and possibly at regular intervals depending on how it is set up.

第二个甚至更多的问题要中止循环,您必须将代码放入循环中.关键是在循环之前先秒表或类似的开始,然后在循环开始时检查已花费了多少时间.如果是一分钟或更长时间,请 break; .

Secondly and more to the point of your question to abort a loop you have to put code inside the loop. The key would be to have a stopwatch or similar start before your loop and then at the beginning of your loop check how much time has elapsed. If it is a minute or more then break;.

要注意的关键是,您不会在一分钟内完全停止,但是您将在分钟结束后结束正在运行的循环的迭代,然后停止.这通常是您想要的,因为在中途停止处理可能会导致令人讨厌的副作用.

The key thing to note is that you will not stop exactly on a minute but you will finish the iteration of the loop that is running when the minute expires and then stop. This is usually what you want since stopping processing midway through something may cause nasty 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);
}

请注意,这里的 Thread.Sleep 只是因为否则我会过快地完成所有90000次迭代.;-)

Note that Thread.Sleep is there just because otherwise I get through all 90000 iterations too quickly. ;-)

这篇关于运行和停止方法一分钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆