Export (0) Print
Expand All

RegexMatchTimeoutException Class

.NET Framework 4.5

The exception that is thrown when the execution time of a regular expression pattern-matching method exceeds its time-out interval.

System.Object
  System.Exception
    System.SystemException
      System.TimeoutException
        System.Text.RegularExpressions.RegexMatchTimeoutException

Namespace:  System.Text.RegularExpressions
Assemblies:   System (in System.dll)
  System.Text.RegularExpressions (in System.Text.RegularExpressions.dll)

[SerializableAttribute]
public class RegexMatchTimeoutException : TimeoutException, 
	ISerializable

The RegexMatchTimeoutException type exposes the following members.

  NameDescription
Public methodSupported in .NET for Windows Store appsRegexMatchTimeoutException()Initializes a new instance of the RegexMatchTimeoutException class with a system-supplied message.
Public methodSupported in .NET for Windows Store appsRegexMatchTimeoutException(String)Initializes a new instance of the RegexMatchTimeoutException class with the specified message string.
Protected methodRegexMatchTimeoutException(SerializationInfo, StreamingContext)Initializes a new instance of the RegexMatchTimeoutException class with serialized data.
Public methodSupported in .NET for Windows Store appsRegexMatchTimeoutException(String, Exception)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.
Public methodSupported in .NET for Windows Store appsRegexMatchTimeoutException(String, String, TimeSpan)Initializes a new instance of the RegexMatchTimeoutException class with information about the regular expression pattern, the input text, and the time-out interval.
Top

  NameDescription
Public propertySupported in .NET for Windows Store appsDataGets a collection of key/value pairs that provide additional user-defined information about the exception. (Inherited from Exception.)
Public propertySupported in .NET for Windows Store appsHelpLinkGets or sets a link to the help file associated with this exception. (Inherited from Exception.)
Public propertySupported in .NET for Windows Store appsHResultGets or sets HRESULT, a coded numerical value that is assigned to a specific exception. (Inherited from Exception.)
Public propertySupported in .NET for Windows Store appsInnerExceptionGets the Exception instance that caused the current exception. (Inherited from Exception.)
Public propertySupported in .NET for Windows Store appsInputGets the input text that the regular expression engine was processing when the time-out occurred.
Public propertySupported in .NET for Windows Store appsMatchTimeoutGets the time-out interval for a regular expression match.
Public propertySupported in .NET for Windows Store appsMessageGets a message that describes the current exception. (Inherited from Exception.)
Public propertySupported in .NET for Windows Store appsPatternGets the regular expression pattern that was used in the matching operation when the time-out occurred.
Public propertySupported in .NET for Windows Store appsSourceGets or sets the name of the application or the object that causes the error. (Inherited from Exception.)
Public propertySupported in .NET for Windows Store appsStackTraceGets a string representation of the immediate frames on the call stack. (Inherited from Exception.)
Public propertyTargetSiteGets the method that throws the current exception. (Inherited from Exception.)
Top

  NameDescription
Public methodSupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported in .NET for Windows Store appsGetBaseExceptionWhen overridden in a derived class, returns the Exception that is the root cause of one or more subsequent exceptions. (Inherited from Exception.)
Public methodSupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodGetObjectDataWhen overridden in a derived class, sets the SerializationInfo with information about the exception. (Inherited from Exception.)
Public methodGetTypeGets the runtime type of the current instance. (Inherited from Exception.)
Protected methodSupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported in .NET for Windows Store appsToStringCreates and returns a string representation of the current exception. (Inherited from Exception.)
Top

  NameDescription
Protected eventSerializeObjectStateOccurs when an exception is serialized to create an exception state object that contains serialized data about the exception. (Inherited from Exception.)
Top

  NameDescription
Explicit interface implemetationPrivate methodISerializable.GetObjectDataPopulates a SerializationInfo object with the data needed to serialize a RegexMatchTimeoutException object.
Top

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. 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. The current time-out interval is available from the MatchTimeout property. 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.

The example in the next section illustrates both techniques for handling a 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. The Regex.IsMatch(String, String, RegexOptions, TimeSpan) method is initially called with a time-out interval of one second. 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.

.NET Framework

Supported in: 4.6, 4.5

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft