在.NET 4中实现正则表达式超时正则表达式、NET

2023-09-02 10:44:56 作者:倾城一夜雪

平台:Silverlight 4中,.NET 4

Platform: Silverlight 4, .NET 4

随着.NET 4.5开发preVIEW的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.