Reputation: 2919
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.
Upvotes: 6
Views: 2113
Reputation: 155493
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.
Upvotes: 6