在.NET 4中实现正则表达式超时 [英] Implementing RegEx Timeout in .NET 4
问题描述
平台:Silverlight 4中,.NET 4
Platform: Silverlight 4, .NET 4
随着.NET 4.5开发preVIEW的<一个href="http://msdn.microsoft.com/en-us/library/system.text.regularex$p$pssions.regex%28v=vs.110%29.aspx">RegEx类已得到增强,允许超时值,这将prevent正则表达式引擎从挂在UI是否有与模式匹配问题的设置。
With the .NET 4.5 Developer preview the RegEx class has been enhanced to allow setting of a Timeout value which would prevent the RegEx engine from hanging the UI if there are issues with the pattern matching.
请求建议在.NET 4 Silverlight应用程序来实现类似的功能。
Requesting suggestions to implement a similar functionality in a .NET 4 Silverlight application.
在此先感谢。
推荐答案
通用例如:
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,异步线程仍然会继续运行。
As pointed out by Christian.K, the async thread will still continue running.
下面是其中的线程将终止:
Here is one where the thread will terminate:
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;
}
更新:
修正上面的代码,以正确处理异常。
Fixed above snippet to deal with exceptions correctly.
这篇关于在.NET 4中实现正则表达式超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!