Suppose I have a C# program where at one point there is the following:
string dato;
dato = recogerDato();
SiguientePantalla("pantalla2.aspx");
Within the collectData() method there may be a query to a database, or a calculation that may take a long time. Inside the NextScreen() method there is a code where the server takes us to another .aspx form
Is there a way to control with some timer or other instruction the time it takes to execute the fetchData() or NextScreen() method and in case let's say it will take more than 15 seconds, it will interrupt the process with an exception or something similar to show a " Timeout too long" and then run it again if we wanted to?
It can be implemented with the Join method of the System.Threading.Thread class .
The code snippet would be as follows, where:
A thread is instantiated to execute the method that takes a long time and that you want to abort (in the example its method collectData)
A TimeSpan is instantiated with the maximum amount of time to wait for the execution (15 seconds for this example)
Method execution is started by the background thread
The Join method is called on the thread, which blocks the main thread for the indicated time (in the TimeSpan that is passed by parameter). The Join method returns true if it finished executing in less than the indicated time, false if it takes more time
The thread (th) that is executing the collectData() method in the background is aborted. Note that calling the Abort method will throw a ThreadAbortException on the thread being aborted.
For the execution of its NextScreen method, which apparently receives a string parameter, the same code fragment above is used with the following modifications:
Instantiate a ParameterizedThreadStart delegate to invoke the NextScreen method
Instantiate the Thread class but to execute a parameterized method
When starting the thread you have to pass the desired parameters, in your case the string "screen2.aspx"