RegexMatchTimeoutException RegexMatchTimeoutException RegexMatchTimeoutException RegexMatchTimeoutException Class

定義

當規則運算式模式比對方法的執行時間超過其逾時間隔時,所擲回的例外狀況。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方法來處理例外狀況。The following example illustrates two possible approaches to handling the RegexMatchTimeoutException exception. 常數, 其值為兩秒, 定義最大逾時間隔。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. 當擲回例外狀況時, 正則運算式引擎會維護其狀態, 讓任何未來的調用都傳回相同的結果, 就像例外狀況並未發生。 RegexMatchTimeoutExceptionWhen 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() RegexMatchTimeoutException() RegexMatchTimeoutException()

使用系統提供的訊息,初始化 RegexMatchTimeoutException 類別的新執行個體。Initializes a new instance of the RegexMatchTimeoutException class with a system-supplied message.

RegexMatchTimeoutException(SerializationInfo, StreamingContext) RegexMatchTimeoutException(SerializationInfo, StreamingContext) RegexMatchTimeoutException(SerializationInfo, StreamingContext) RegexMatchTimeoutException(SerializationInfo, StreamingContext)

使用序列化資料,初始化 RegexMatchTimeoutException 類別的新執行個體。Initializes a new instance of the RegexMatchTimeoutException class with serialized data.

RegexMatchTimeoutException(String) RegexMatchTimeoutException(String) RegexMatchTimeoutException(String) RegexMatchTimeoutException(String)

使用指定的訊息字串,初始化 RegexMatchTimeoutException 類別的新執行個體。Initializes a new instance of the RegexMatchTimeoutException class with the specified message string.

RegexMatchTimeoutException(String, Exception) RegexMatchTimeoutException(String, Exception) RegexMatchTimeoutException(String, Exception) 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(String, String, TimeSpan) RegexMatchTimeoutException(String, String, TimeSpan) 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 Data Data Data

取得提供例外狀況之其他使用者定義相關資訊的索引鍵/值組集合。Gets a collection of key/value pairs that provide additional user-defined information about the exception.

(Inherited from Exception)
HelpLink HelpLink HelpLink HelpLink

取得或設定與這個例外狀況相關聯的說明檔連結。Gets or sets a link to the help file associated with this exception.

(Inherited from Exception)
HResult HResult HResult HResult

取得或設定 HRESULT,它是指派給特定例外狀況的編碼數值。Gets or sets HRESULT, a coded numerical value that is assigned to a specific exception.

(Inherited from Exception)
InnerException InnerException InnerException InnerException

取得造成目前例外狀況的 Exception 執行個體。Gets the Exception instance that caused the current exception.

(Inherited from Exception)
Input Input Input Input

取得當發生逾時,規則運算式引擎所處理的輸入文字。Gets the input text that the regular expression engine was processing when the time-out occurred.

MatchTimeout MatchTimeout MatchTimeout MatchTimeout

取得規則運算式比對的逾時間隔。Gets the time-out interval for a regular expression match.

Message Message Message Message

取得描述目前例外狀況的訊息。Gets a message that describes the current exception.

(Inherited from Exception)
Pattern Pattern Pattern Pattern

取得當發生逾時,比對作業中所使用的規則運算式模式。Gets the regular expression pattern that was used in the matching operation when the time-out occurred.

Source Source Source Source

取得或設定造成錯誤的應用程式或物件的名稱。Gets or sets the name of the application or the object that causes the error.

(Inherited from Exception)
StackTrace StackTrace StackTrace StackTrace

取得呼叫堆疊上即時運算框架的字串表示。Gets a string representation of the immediate frames on the call stack.

(Inherited from Exception)
TargetSite TargetSite TargetSite TargetSite

取得擲回目前例外狀況的方法。Gets the method that throws the current exception.

(Inherited from Exception)

明確介面實作

ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext) ISerializable.GetObjectData(SerializationInfo, StreamingContext)

將序列化 SerializationInfo 物所需的資料填入 RegexMatchTimeoutException 物件。Populates a SerializationInfo object with the data needed to serialize a RegexMatchTimeoutException object.

方法

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetBaseException() GetBaseException() GetBaseException() GetBaseException()

在衍生類別中覆寫時,傳回一或多個後續的例外狀況的根本原因 ExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions.

(Inherited from Exception)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為預設雜湊函式。Serves as the default hash function.

(Inherited from Object)
GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext) GetObjectData(SerializationInfo, StreamingContext)

在衍生類別中覆寫時,使用例外狀況的資訊設定 SerializationInfoWhen overridden in a derived class, sets the SerializationInfo with information about the exception.

(Inherited from Exception)
GetType() GetType() GetType() GetType()

取得目前執行個體的執行階段類型。Gets the runtime type of the current instance.

(Inherited from Exception)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

建立並傳回目前例外狀況的字串表示。Creates and returns a string representation of the current exception.

(Inherited from Exception)

事件

SerializeObjectState SerializeObjectState SerializeObjectState SerializeObjectState

當例外狀況序列化,以建立包含例外狀況相關序列化資料的例外狀況狀態物件時,就會發生此事件。Occurs when an exception is serialized to create an exception state object that contains serialized data about the exception.

(Inherited from Exception)

適用於

另請參閱