平台:Silverlight 4,.NET 4
使用.NET 4.5 Developer预览版,RegEx类已得到增强,允许设置Timeout值,如果模式匹配存在问题,将阻止RegEx引擎挂起UI.
请求在.NET 4 Silverlight应用程序中实现类似功能的建议.
提前致谢.
解决方法
通用示例:
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(); }
用法:
var r = WithTimeout(() => regex.Match(foo),1000);
更新:
正如Christian.K所指出的,异步线程仍将继续运行.
这是线程终止的地方:
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(); // not sure if this is really needed in general while (t.ThreadState != ThreadState.Running) { Thread.Sleep(0); } if (!reset.WaitOne(duration)) { t.Abort(); throw new TimeoutException(); } if (ex != null) { throw ex; } return r; }
更新:
修复了上面的代码段以正确处理异常.