使用正则匹配比较大的数据时就会发生程序超时并没有异常弹出,而且电脑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 ///2 /// 正则解析 3 /// 4 /// 正则对象 5 /// 需要解析的字符串 6 /// 超时时间 7 ///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 /// 25 /// 等待方法执行完成,或超时 26 /// 27 /// 28 /// 29 /// 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 ///46 /// 正则解析 47 /// 48 /// 正则对象 49 /// 需要解析的字符串 50 /// 超时时间 51 ///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 }