正则匹配超时处理

使用正则匹配比较大的数据时就会发生程序超时并没有异常弹出,而且电脑cpu会到达100%

在.Net4.5中微软有改进的方法,直接调用很方便,但.Net4.5以下就没有,下面写下自己找的处理方法

1、.Net4.5中:  

Regex reg = new Regex(正则, RegexOptions.IgnoreCase, TimeSpan.FromSeconds(2));

TimeSpan.FromSeconds就是设置的超时时间,如超过就返回为空,FromSeconds=2是秒,也可以设置分钟小时

2、.Net4.0中:

 1 /// <summary>

 2         /// 正则解析

 3         /// </summary>

 4         /// <param name="regex">正则对象</param>

 5         /// <param name="input">需要解析的字符串</param>

 6         /// <param name="OutTimeMilliseconds">超时时间</param>

 7         /// <returns></returns>

 8         public static MatchCollection Matchs(Regex regex, string input, int OutTimeMilliseconds)

 9         {

10             MatchCollection mc = null;

11             AutoResetEvent are = new AutoResetEvent(false);

12             Thread t = new Thread(delegate()

13             {

14                 mc = regex.Matches(input);

15                 //注意,在这里一定要把所有的匹配项遍历一次,不然的话当在此方法外遍历的话.也可能会出现等待情况

16                 foreach (Match m in mc) { }

17                 are.Set();

18             });

19             t.Start();

20             Wait(t, TimeSpan.FromMilliseconds(OutTimeMilliseconds), are, null);

21             return mc;

22         }

23 

24         /// <summary>

25         /// 等待方法执行完成,或超时

26         /// </summary>

27         /// <param name="t"></param>

28         /// <param name="OutTime"></param>

29         /// <param name="ares"></param>

30         private static void Wait(Thread t, TimeSpan OutTime, WaitHandle are, WaitHandle cancelEvent)

31         {

32             WaitHandle[] ares;

33             if (cancelEvent == null)

34                 ares = new WaitHandle[] { are };

35             else

36                 ares = new WaitHandle[] { are, cancelEvent };

37             int index = WaitHandle.WaitAny(ares, OutTime);

38             if ((index != 0) && t.IsAlive)//如果不是执行完成的信号,并且,线程还在执行,那么,结束这个线程

39             {

40                 t.Abort();

41                 t = null;

42             }

43         }

44 

45         /// <summary>

46         /// 正则解析

47         /// </summary>

48         /// <param name="regex">正则对象</param>

49         /// <param name="input">需要解析的字符串</param>

50         /// <param name="OutTimeMilliseconds">超时时间</param>

51         /// <returns></returns>

52         public static Match Match(Regex regex, string input, int OutTimeMilliseconds)

53         {

54             Match m = null;

55             AutoResetEvent are = new AutoResetEvent(false);

56             Thread t = new Thread(delegate() { m = regex.Match(input); are.Set(); });

57             t.Start();

58             Wait(t, TimeSpan.FromMilliseconds(OutTimeMilliseconds), are, null);

59             return m;

60         }
View Code

 

你可能感兴趣的:(正则)