运行 在 windows 表单应用程序 C# 中使用定时器的特定时间循环

Running a loop for specific time using timer in windows form application C#

我正在尝试在特定时间内重复进行一些计算(time 是可变的,由用户提供。)

我尝试使用 windows 表单应用程序工具箱中可用的计时器 visual studio,但似乎有问题。当我启动计时器并将 time 的变量与 while 循环相关联时,程序卡住了; time 变量在计时器的每个滴答事件中递减,只要时间大于 0,我就需要 运行 while 循环。

private void timer1_Tick(object sender, EventArgs e)
    {
        if (time == 0)
            timer1.Stop();

        else
        {
            time--;
            textBoxTime.Text = time.ToString();
        }

    }

这是阻塞程序的 while 循环

while (time>0)
{
   computations();
}

您可以为此使用计时器 class 一个简单的示例是这样的:

Clock=new Timer();
Clock.Interval=time;
Clock.Start();
Clock.Tick+=new EventHandler(OnTimer_Tick);

其中 OnTimer_Tick 是一个做一些工作的函数

public void OnTimer_Tick(object sender,EventArgs eArgs)
{
//do computations here
}

这里是相关的SO post

编辑:您的 while 循环 运行 比 tick 快,因此您 运行 循环很多。我更新了计时器以使用时间变量作为它的间隔值并摆脱 while 循环并在每个滴答时进行计算。

i'm trying to make some calculations repeatedly for a specific amount of time the time is variable and provided by the user.

与其使用定时器来为你计时,我建议你在循环开始时记录下它的时间,在每次循环迭代时检查当前时间,看看它是否已经 运行够长了。

and here is the while loop that blocks the program

推测您正在对 UI 线程执行计算。这将阻止处理任何 UI 消息,包括计时器滴答,从而使应用程序无响应。

启动一个单独的线程来执行实际计算。 BackgroundWorker 是从 WinForms 执行此操作的常用方法,尽管有很多方法。

您可以使用 Stopwatch

另外最好循环休眠以避免占用你所有的机器资源

 var sw = new Stopwatch();
 sw.Start();
 while(sw.Elapsed.TotalSeconds < 100 /*Time in second*/)
 {
    /// TODO
    Thread.Sleep(100 /*Time in millisecond*/);
 }
 sw.Stop();