Implementing RegEx Timeout in .NET 4

后端 未结 4 1710
情歌与酒
情歌与酒 2020-12-09 00:33

Platform: Silverlight 4, .NET 4

With the .NET 4.5 Developer preview the RegEx class has been enhanced to allow setting of a Timeout value which would prevent the Reg

4条回答
  •  天命终不由人
    2020-12-09 00:59

    Generic example:

    public static R WithTimeout(Func proc, int duration)
    {
      var wh = proc.BeginInvoke(null, null);
    
      if (wh.AsyncWaitHandle.WaitOne(duration))
      {
        return proc.EndInvoke(wh);
      }
    
      throw new TimeOutException();
    }
    

    Usage:

    var r = WithTimeout(() => regex.Match(foo), 1000);
    

    Update:

    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(Func 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;
    }
    

    Update:

    Fixed above snippet to deal with exceptions correctly.

提交回复
热议问题