//
try the five second method with a 6 second timeout
CallWithTimeout(FiveSecondMethod,
6000
);
//
try the five second method with a 4 second timeout
//
this will throw a timeout exception
CallWithTimeout(FiveSecondMethod,
4000
);
static
void
FiveSecondMethod()
Thread.Sleep(
5000
);
static
void
CallWithTimeout(Action action,
int
timeoutMilliseconds)
Thread threadToKill
=
null
;
Action wrappedAction
= () =>
threadToKill
=
Thread.CurrentThread;
action();
IAsyncResult result
= wrappedAction.BeginInvoke(
null
,
null
);
if
(result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
wrappedAction.EndInvoke(result);
threadToKill.Abort();
throw
new
TimeoutException();