Stop running the code after 15 seconds

后端 未结 3 1552
北荒
北荒 2020-12-17 04:03

I\'m trying to write something to stop running the code after 15 seconds of running.

I don\'t want While loop or any kind of loop to be used and would l

3条回答
  •  有刺的猬
    2020-12-17 04:50

    You can assign DateTime variable before the loop having the current date and time, then in each loop iteration simply check if 15 seconds have passed:

    DateTime start = DateTime.Now;
    for (int i = 1; i < 100000; i++)
    {
        if ((DateTime.Now - start).TotalSeconds >= 15)
            break;
        Console.WriteLine("This is test no. "+ i+ "\n");
    }
    

    Update: while the above will usually work, it's not bullet proof and might fail on some edge cases (as Servy pointed out in a comment), causing endless loop. Better practice would be using the Stopwatch class, which is part of System.Diagnostics namespace:

    Stopwatch watch = new Stopwatch();
    watch.Start();
    for (int i = 1; i < 100000; i++)
    {
        if (watch.Elapsed.TotalMilliseconds >= 500)
            break;
        Console.WriteLine("This is test no. " + i + "\n");
    }
    watch.Stop();
    

提交回复
热议问题