RegexMatchTimeoutException 클래스

정의

정적 정규식 패턴 일치 메서드의 실행 시간이 시간 제한 간격을 초과하는 경우 throw되는 예외입니다.

public ref class RegexMatchTimeoutException : TimeoutException
public class RegexMatchTimeoutException : TimeoutException
[System.Serializable]
public class RegexMatchTimeoutException : TimeoutException
type RegexMatchTimeoutException = class
    inherit TimeoutException
type RegexMatchTimeoutException = class
    inherit TimeoutException
    interface ISerializable
[<System.Serializable>]
type RegexMatchTimeoutException = class
    inherit TimeoutException
    interface ISerializable
Public Class RegexMatchTimeoutException
Inherits TimeoutException
상속
RegexMatchTimeoutException
상속
RegexMatchTimeoutException
특성
구현

예제

다음 예제에서는 예외를 처리할 수 있는 두 가지 방법을 보여 줍니다 RegexMatchTimeoutException . 값이 2초인 상수는 최대 제한 시간 간격을 정의합니다. Regex.IsMatch(String, String, RegexOptions, TimeSpan) 메서드는 처음에 1초의 제한 시간 간격으로 호출됩니다. 각 RegexMatchTimeoutException 예외로 인해 제한 시간 간격이 1초씩 증가하고 현재 시간 제한 간격이 최대 제한 시간 간격보다 작으면 메서드에 대한 또 다른 호출 Regex.IsMatch 이 발생합니다. 그러나 현재 제한 시간 간격이 최대 제한 시간 간격을 초과하는 경우 예외 처리기는 이벤트 로그에 정보를 쓰고 정규식 처리를 중단합니다.

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 있으면 일반적으로 다음 조건 중 하나를 나타냅니다.

  • 정규식 엔진은 입력 텍스트를 정규식 패턴과 일치시키려고 할 때 지나치게 역추적합니다.

  • 특히 컴퓨터 부하가 높은 경우 제한 시간 간격이 너무 낮게 설정되었습니다.

예외 처리기가 예외를 처리하는 방법은 예외의 원인에 따라 달라집니다.

  • 과도한 역추적으로 인해 시간 초과가 발생하는 경우 예외 처리기는 입력 일치 시도를 포기하고 정규식 패턴 일치 메서드에서 시간 초과가 발생했음을 사용자에게 알려야 합니다. 가능한 경우 속성에서 사용할 수 있는 정규식 패턴 및 속성에서 Pattern Input 사용할 수 있는 과도한 역추적을 발생시킨 입력에 대한 정보를 기록하여 문제를 조사하고 정규식 패턴을 수정해야 합니다. 과도한 역추적으로 인한 시간 제한은 항상 재현할 수 있습니다.

  • 제한 시간 임계값을 너무 낮게 설정하여 시간 초과가 발생하는 경우 시간 제한 간격을 늘리고 일치 작업을 다시 시도할 수 있습니다. 현재 제한 시간 간격은 속성에서 MatchTimeout 사용할 수 있습니다. 예외가 RegexMatchTimeoutException throw되면 정규식 엔진은 해당 상태를 유지 관리하므로 이후 호출에서 예외가 발생하지 않은 것처럼 동일한 결과를 반환합니다. 일치하는 메서드를 다시 호출하기 전에 예외가 throw된 후 짧은 임의 시간 간격을 기다리는 것이 좋습니다. 이 작업은 여러 번 반복될 수 있습니다. 그러나 과도한 역추적으로 인해 시간 초과가 발생하는 경우 반복 횟수가 작아야 합니다.

다음 섹션의 예제에서는 을 처리하는 RegexMatchTimeoutException두 가지 기술을 보여 줍니다.

생성자

RegexMatchTimeoutException()

시스템 제공 메시지를 사용하여 RegexMatchTimeoutException 클래스의 새 인스턴스를 초기화합니다.

RegexMatchTimeoutException(SerializationInfo, StreamingContext)

serialize된 데이터를 사용하여 RegexMatchTimeoutException 클래스의 새 인스턴스를 초기화합니다.

RegexMatchTimeoutException(String)

지정된 메시지 문자열을 사용하여 RegexMatchTimeoutException 클래스의 새 인스턴스를 초기화합니다.

RegexMatchTimeoutException(String, Exception)

지정된 오류 메시지와 해당 예외의 원인인 내부 예외에 대한 참조를 사용하여 RegexMatchTimeoutException 클래스의 새 인스턴스를 초기화합니다.

RegexMatchTimeoutException(String, String, TimeSpan)

정규식 패턴, 입력 텍스트 및 시간 초과 간격에 대한 정보를 사용하여 RegexMatchTimeoutException 클래스의 새 인스턴스를 초기화합니다.

속성

Data

예외에 대한 사용자 정의 정보를 추가로 제공하는 키/값 쌍 컬렉션을 가져옵니다.

(다음에서 상속됨 Exception)
HelpLink

이 예외와 연결된 도움말 파일에 대한 링크를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
HResult

특정 예외에 할당된 코드화된 숫자 값인 HRESULT를 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
InnerException

현재 예외를 발생시킨 Exception 인스턴스를 가져옵니다.

(다음에서 상속됨 Exception)
Input

제한 시간이 경과될 때 정규식 엔진에서 처리하고 있었던 입력 텍스트를 가져옵니다.

MatchTimeout

정규식 일치에 대한 시간 제한 간격을 가져옵니다.

Message

현재 예외를 설명하는 메시지를 가져옵니다.

(다음에서 상속됨 Exception)
Pattern

제한 시간이 초과될 때 일치하는 작업에서 사용된 정규식 패턴을 가져옵니다.

Source

오류를 발생시키는 애플리케이션 또는 개체의 이름을 가져오거나 설정합니다.

(다음에서 상속됨 Exception)
StackTrace

호출 스택의 직접 실행 프레임 문자열 표현을 가져옵니다.

(다음에서 상속됨 Exception)
TargetSite

현재 예외를 throw하는 메서드를 가져옵니다.

(다음에서 상속됨 Exception)

메서드

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

(다음에서 상속됨 Object)
GetBaseException()

파생 클래스에서 재정의된 경우 하나 이상의 후속 예외의 근본 원인이 되는 Exception 을 반환합니다.

(다음에서 상속됨 Exception)
GetHashCode()

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetObjectData(SerializationInfo, StreamingContext)

파생 클래스에서 재정의된 경우 예외에 관한 정보를 SerializationInfo 에 설정합니다.

(다음에서 상속됨 Exception)
GetType()

현재 인스턴스의 런타임 형식을 가져옵니다.

(다음에서 상속됨 Exception)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

현재 예외에 대한 문자열 표현을 만들고 반환합니다.

(다음에서 상속됨 Exception)

이벤트

SerializeObjectState
사용되지 않습니다.

예외에 대한 serialize된 데이터가 들어 있는 예외 상태 개체가 만들어지도록 예외가 serialize될 때 발생합니다.

(다음에서 상속됨 Exception)

명시적 인터페이스 구현

ISerializable.GetObjectData(SerializationInfo, StreamingContext)

SerializationInfo 개체를 serialize하는 데 필요한 데이터로 RegexMatchTimeoutException 개체를 채웁니다.

적용 대상

추가 정보