Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The best way in C# to stop function in middle is the <code>return</code> keyword in function, but how do I know when to use the <code>return</code> keyword to stop the function in middle, after it lasts at least 3 seconds? The <code>Stopwatch</code> class from <code>System.Diagnostics</code> 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 <code>Stopwatch</code> using <code>System.Diagnostics</code> with the <code>new</code> keyword, start it by calling the <code>Start()</code> function of the Stopwatch class, and in for each loop and loop, at the beginning, add the following code: </p> <pre><code>if (stopwatch.ElapsedMilliseconds &gt;= 3000) { stopwatch.Stop(); // or stopwatch.Reset(); return; } </code></pre> <p>(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 <code>IsRunning</code> of the Stopwatch class. After that ask if elapsed time is more than 3 seconds, and if yes (<code>true</code>) stop or reset the Stopwatch, and use the <code>return</code> 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!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload