The best way in C# to stop function in middle is the return
keyword in function, but how do I know when to use the return
keyword to stop the function in middle, after it lasts at least 3 seconds? The Stopwatch
class from System.Diagnostics
is the answer. This complicated function that lasts between 2 seconds to 5 minutes (depending on the input data) logically uses many loops, and maybe even recursion, so my solution for you is that, at the first line code of that function, create an instance of Stopwatch
using System.Diagnostics
with the new
keyword, start it by calling the Start()
function of the Stopwatch class, and in for each loop and loop, at the beginning, add the following code:
if (stopwatch.ElapsedMilliseconds >= 3000) {
stopwatch.Stop();
// or
stopwatch.Reset();
return;
}
(tip: you can type it with hands once, copy it Ctrl+C, and then just paste it Ctrl+V). If that function uses recursion, in order to save memory, make the Stopwatch global instance rather than creating it as local instance at first, and start it if it does not running at the beginning of the code. You can know that with the IsRunning
of the Stopwatch class. After that ask if elapsed time is more than 3 seconds, and if yes (true
) stop or reset the Stopwatch, and use the return
keyword to stop the recursion loop, very good start in function, if your function lasts long time due mainly recursion more than loops. That it is. As you can see, it is very simple, and I tested this solution, and the results showed that it works! Try it yourself!