I cannot imagine why it can be useful; it sounds like a abuse to me.
Anyway, the best way to do it is using
System.Diagnostics.Stopwatch
. You start it before loop and check in loop and break it when it's time to break:
Stopwatch Class (System.Diagnostics)[
^].
Of course, the accuracy cannot be better than the time of a single iteration. You can also check up time several times in different part of the code of the iteration. Ultimately, if the code is highly structured, you can have checkup on different places and different levels and, instead of break, throw a custom exception, which you can catch outside the loop. If the time spend inside a single iteration is considerable, it can give you much better precision, but you may loose some side effect you would need to complete in each iteration. In other words, you need to design it.
Another approach with better accuracy could be having a separate thread which you could abort by an outside timer, but this approach is risky unless you really deeply understand the technology and are extremely careful.
—SA