General example:
public static R WithTimeout<R>(Func<R> proc, int duration) { var wh = proc.BeginInvoke(null, null); if (wh.AsyncWaitHandle.WaitOne(duration)) { return proc.EndInvoke(wh); } throw new TimeOutException(); }
Application:
var r = WithTimeout(() => regex.Match(foo), 1000);
Update:
As pointed out by Christian.K, the asynchronous thread will continue to work.
This is where the stream ends:
public static R WithTimeout<R>(Func<R> proc, int duration) { var reset = new AutoResetEvent(false); var r = default(R); Exception ex = null; var t = new Thread(() => { try { r = proc(); } catch (Exception e) { ex = e; } reset.Set(); }); t.Start();
Update:
Fixed above snippet to handle exceptions correctly.
source share