RegexMatchTimeoutException 类

定义

正则表达式模式匹配方法的执行时间超出其超时时间间隔时引发的异常。The exception that is thrown when the execution time of a regular expression pattern-matching method exceeds its time-out interval.

public ref class RegexMatchTimeoutException : TimeoutException
[System.Serializable]
public class RegexMatchTimeoutException : TimeoutException
type RegexMatchTimeoutException = class
    inherit TimeoutException
    interface ISerializable
Public Class RegexMatchTimeoutException
Inherits TimeoutException
继承
RegexMatchTimeoutException
属性
实现

示例

下面的示例演示了两种处理 RegexMatchTimeoutException 异常的可能方法。The following example illustrates two possible approaches to handling the RegexMatchTimeoutException exception. 一个常数,其值为2秒,用于定义最大超时间隔。A constant whose value is two seconds defines the maximum time-out interval. 最初使用一秒的超时间隔调用 Regex.IsMatch(String, String, RegexOptions, TimeSpan) 方法。The Regex.IsMatch(String, String, RegexOptions, TimeSpan) method is initially called with a time-out interval of one second. 每个 RegexMatchTimeoutException 异常都会导致超时间隔增加一秒,如果当前超时间隔小于最大超时间隔,则会导致另一次调用 Regex.IsMatch 方法。Each RegexMatchTimeoutException exception causes the time-out interval to be increased by one second and results in another call to the Regex.IsMatch method if the current time-out interval is less than the maximum time-out interval. 但是,如果当前超时间隔超出最大超时间隔,异常处理程序会将信息写入事件日志,并放弃正则表达式的处理。However, if the current time-out interval exceeds the maximum time-out interval, the exception handler writes information to the event log and abandons the processing of the regular expression.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;

public class Example
{
   const int MaxTimeoutInSeconds = 2;
   
   public static void Main()
   {
      TimeSpan timeout = new TimeSpan(0, 0, 1);
      string input = "aaaaaaaaaaaaaaaaaaaaaa>";
      if (ValidateInput(input, timeout))
         // Perform some operation with valid input string.
         Console.WriteLine("'{0}' is a valid string.", input); 
   } 

   private static bool ValidateInput(string input, TimeSpan timeout)
   {
      string pattern = "(a+)+$";      
      try {
         return Regex.IsMatch(input, pattern, 
                              RegexOptions.IgnoreCase, timeout);
      }
      catch (RegexMatchTimeoutException e) {
         // Increase the timeout interval and retry.
         timeout = timeout.Add(new TimeSpan(0, 0, 1));
         Console.WriteLine("Changing the timeout interval to {0}", 
                           timeout); 
         if (timeout.TotalSeconds <= MaxTimeoutInSeconds) {
            // Pause for a short period.
            Thread.Sleep(250);
            return ValidateInput(input, timeout);
         }   
         else {
            Console.WriteLine("Timeout interval of {0} exceeded.", 
                              timeout);
            // Write to event log named RegexTimeouts
            try {
               if (! EventLog.SourceExists("RegexTimeouts"))
                  EventLog.CreateEventSource("RegexTimeouts", "RegexTimeouts");

               EventLog log = new EventLog("RegexTimeouts");
               log.Source = "RegexTimeouts";
               string msg = String.Format("Timeout after {0} matching '{1}' with '{2}.",
                                          e.MatchTimeout, e.Input, e.Pattern);
               log.WriteEntry(msg, EventLogEntryType.Error);
            }
            // Do nothing to handle the exceptions.
            catch (SecurityException) { }
            catch (InvalidOperationException) { }
            catch (Win32Exception) { }
            return false;
         }   
      }
   }
}
// The example writes to the event log and also displays the following output:
//       Changing the timeout interval to 00:00:02
//       Changing the timeout interval to 00:00:03
//       Timeout interval of 00:00:03 exceeded.
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.Security
Imports System.Text.RegularExpressions
Imports System.Threading

Module Example
   Const MaxTimeoutInSeconds As Integer = 2
   
   Public Sub Main()
      Dim timeout As TimeSpan = New TimeSpan(0, 0, 1)
      
      Dim input As String = "aaaaaaaaaaaaaaaaaaaaaa>"
      If ValidateInput(input, timeout) Then
         ' Perform some operation with valid input string.
         Console.WriteLine("'{0}' is a valid string.", input) 
      End If
   End Sub 

   Private Function ValidateInput(input As String, 
                                  timeout As TimeSpan) As Boolean
      Dim pattern As String = "(a+)+$"      
      Try
         Return Regex.IsMatch(input, pattern, 
                              RegexOptions.IgnoreCase, timeout)
      Catch e As RegexMatchTimeoutException
         ' Increase the timeout interval and retry.
         timeout = timeout.Add(New TimeSpan(0, 0, 1))
         Console.WriteLine("Changing the timeout interval to {0}", 
                           timeout) 
         If timeout.TotalSeconds <= MaxTimeoutInSeconds Then
            ' Pause for a short interval.
            Thread.Sleep(250)
            Return ValidateInput(input, timeout)
         Else
            Console.WriteLine("Timeout interval of {0} exceeded.", 
                              timeout)
            ' Write to event log named RegexTimeouts
            Try
               If Not EventLog.SourceExists("RegexTimeouts") Then
                  EventLog.CreateEventSource("RegexTimeouts", "RegexTimeouts")
               End If   
               Dim log As New EventLog("RegexTimeouts")
               log.Source = "RegexTimeouts"
               Dim msg As String = String.Format("Timeout after {0} matching '{1}' with '{2}.",
                                                 e.MatchTimeout, e.Input, e.Pattern)
               log.WriteEntry(msg, EventLogEntryType.Error)
            ' Do nothing to handle the exceptions.
            Catch ex As SecurityException

            Catch ex As InvalidOperationException

            Catch ex As Win32Exception

            End Try   
            Return False
         End If   
      End Try
   End Function
End Module
' The example writes to the event log and also displays the following output:
'       Changing the timeout interval to 00:00:02
'       Changing the timeout interval to 00:00:03
'       Timeout interval of 00:00:03 exceeded.

注解

出现 RegexMatchTimeoutException 异常通常表明存在下列情况之一:The presence of a RegexMatchTimeoutException exception generally indicates one of the following conditions:

  • 正则表达式引擎尝试将输入文本与正则表达式模式匹配时,会过度进行回溯。The regular expression engine is backtracking excessively as it attempts to match the input text to the regular expression pattern.

  • 超时间隔设置得太低,特别是对于高计算机负载。The time-out interval has been set too low, especially given high machine load.

异常处理程序处理异常的方式取决于异常的原因:The way in which an exception handler handles an exception depends on the cause of the exception:

  • 如果超时导致过多回溯,则异常处理程序应放弃与输入的尝试匹配,并通知用户在正则表达式模式匹配方法中发生了超时。If the time-out results from excessive backtracking, your exception handler should abandon the attempt to match the input and inform the user that a time-out has occurred in the regular expression pattern-matching method. 如果可能,应记录有关正则表达式模式的信息,该模式可从 "Pattern" 属性获取,而导致过多回溯(可从 "Input" 属性获取)的情况下,应进行记录,以便能够调查问题并修改正则表达式模式。If possible, information about the regular expression pattern, which is available from the Pattern property, and the input that caused excessive backtracking, which is available from the Input property, should be logged so that the issue can be investigated and the regular expression pattern modified. 由于回溯过多,超时始终是可重复的。Time-outs due to excessive backtracking are always reproducible.

  • 如果将超时阈值设置得太低,则可以增加超时间隔,然后重试匹配操作。If the time-out results from setting the time-out threshold too low, you can increase the time-out interval and retry the matching operation. 当前超时间隔可从 MatchTimeout 属性获取。The current time-out interval is available from the MatchTimeout property. 当引发 RegexMatchTimeoutException 异常时,正则表达式引擎将保留其状态,以便以后的任何调用返回相同的结果,就好像未发生异常一样。When a RegexMatchTimeoutException exception is thrown, the regular expression engine maintains its state so that any future invocations return the same result, as if the exception did not occur. 建议的模式是在引发异常之后等待短暂的随机时间间隔,然后再次调用匹配方法。The recommended pattern is to wait for a brief, random time interval after the exception is thrown before calling the matching method again. 这可以重复多次。This can be repeated several times. 但是,重复次数应为小,以防过度回溯导致超时。However, the number of repetitions should be small in case the time-out is caused by excessive backtracking.

下一节中的示例说明了用于处理 RegexMatchTimeoutException的两种方法。The example in the next section illustrates both techniques for handling a RegexMatchTimeoutException.

构造函数

RegexMatchTimeoutException()

使用由系统提供的消息初始化 RegexMatchTimeoutException 类的新实例。Initializes a new instance of the RegexMatchTimeoutException class with a system-supplied message.

RegexMatchTimeoutException(SerializationInfo, StreamingContext)

使用序列化数据初始化 RegexMatchTimeoutException 类的新实例。Initializes a new instance of the RegexMatchTimeoutException class with serialized data.

RegexMatchTimeoutException(String)

使用指定的消息字符串初始化 RegexMatchTimeoutException 类的新实例。Initializes a new instance of the RegexMatchTimeoutException class with the specified message string.

RegexMatchTimeoutException(String, Exception)

使用指定的错误消息和对作为此异常原因的内部异常的引用来初始化 RegexMatchTimeoutException 类的新实例。Initializes a new instance of the RegexMatchTimeoutException class with a specified error message and a reference to the inner exception that is the cause of this exception.

RegexMatchTimeoutException(String, String, TimeSpan)

使用有关正则表达式模式、输入文本和超时间隔的信息初始化 RegexMatchTimeoutException 类的新实例。Initializes a new instance of the RegexMatchTimeoutException class with information about the regular expression pattern, the input text, and the time-out interval.

属性

Data

获取键/值对的集合,这些键/值对提供有关该异常的其他用户定义信息。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(继承自 Exception)
HelpLink

获取或设置指向与此异常关联的帮助文件链接。Gets or sets a link to the help file associated with this exception.

(继承自 Exception)
HResult

获取或设置 HRESULT(一个分配给特定异常的编码数字值)。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(继承自 Exception)
InnerException

获取导致当前异常的 Exception 实例。Gets the Exception instance that caused the current exception.

(继承自 Exception)
Input

获取超时发生时正则表达式引擎正在处理的输入文本。Gets the input text that the regular expression engine was processing when the time-out occurred.

MatchTimeout

获取正则表达式匹配的超时间隔。Gets the time-out interval for a regular expression match.

Message

获取描述当前异常的消息。Gets a message that describes the current exception.

(继承自 Exception)
Pattern

获取超时发生时用于匹配操作的正则表达式模式。Gets the regular expression pattern that was used in the matching operation when the time-out occurred.

Source

获取或设置导致错误的应用程序或对象的名称。Gets or sets the name of the application or the object that causes the error.

(继承自 Exception)
StackTrace

获取调用堆栈上的即时框架字符串表示形式。Gets a string representation of the immediate frames on the call stack.

(继承自 Exception)
TargetSite

获取引发当前异常的方法。Gets the method that throws the current exception.

(继承自 Exception)

方法

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetBaseException()

当在派生类中重写时,返回 Exception,它是一个或多个并发的异常的根本原因。When overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(继承自 Exception)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetObjectData(SerializationInfo, StreamingContext)

当在派生类中重写时,用关于异常的信息设置 SerializationInfoWhen overridden in a derived class, sets the SerializationInfo with information about the exception.

(继承自 Exception)
GetType()

获取当前实例的运行时类型。Gets the runtime type of the current instance.

(继承自 Exception)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ToString()

创建并返回当前异常的字符串表示形式。Creates and returns a string representation of the current exception.

(继承自 Exception)

事件

SerializeObjectState

当异常被序列化用来创建包含有关该异常的徐列出数据的异常状态对象时会出现该问题。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(继承自 Exception)

显式接口实现

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

使用序列化 SerializationInfo 对象所需的数据填充 RegexMatchTimeoutException 对象。Populates a SerializationInfo object with the data needed to serialize a RegexMatchTimeoutException object.

适用于

另请参阅