Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent an infinite loop in ASP.net

In ASP.NET 4.0 web pages, I would like to detect and prevent code that runs too long. So I'm looking for a construct like this:

try for 1000 ms
{
    RunPotentiallyTooLongCode();
}
catch
{
    RecordError( "code ran out of control" );
    // let user know
    ...
}

Although we're currently using 4.0, I would also be interested in solutions for 4.5, perhaps the async features added would help.

like image 514
Knox Avatar asked Sep 05 '12 13:09

Knox


1 Answers

You'd spawn a new thread for the long-running task, then block and wait for that thread to complete or until a timeout has been reached. If the timeout was reached then the task has presumably blocked (either an infinite loop, a deadlock, or a blocking IO wait) and you can terminate the thread.

Thread thread = new Thread( RunPotentiallyTooLongCode );
thread.Start();
Boolean success = thread.Join( 1000 );
if( !success ) thread.Abort();

There's no need to use the 4.0 async stuff here. In fact this code will run fine on .NET 1.0 too.

like image 146
Dai Avatar answered Oct 26 '22 17:10

Dai