Vai*_*hav 8 .net c# regex silverlight timeout
平台:Silverlight 4,.NET 4
使用.NET 4.5 Developer预览版,RegEx类已得到增强,允许设置Timeout值,如果模式匹配存在问题,将阻止RegEx引擎挂起UI.
请求在.NET 4 Silverlight应用程序中实现类似功能的建议.
提前致谢.
lep*_*pie 12
通用示例:
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();
}
Run Code Online (Sandbox Code Playgroud)
用法:
var r = WithTimeout(() => regex.Match(foo), 1000);
Run Code Online (Sandbox Code Playgroud)
更新:
正如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;
}
Run Code Online (Sandbox Code Playgroud)
更新:
修复了上面的代码段以正确处理异常.
归档时间: |
|
查看次数: |
5135 次 |
最近记录: |