在 .NET 4 中实现 RegEx 超时 [英] Implementing RegEx Timeout in .NET 4

查看:10
本文介绍了在 .NET 4 中实现 RegEx 超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

平台:Silverlight 4、.NET 4

Platform: Silverlight 4, .NET 4

使用 .NET 4.5 开发人员预览版 RegEx 类已得到增强,允许设置超时值,如果模式匹配出现问题,这将防止 RegEx 引擎挂起 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 中实现 RegEx 超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆