使用正则匹配比较大的数据时就会发生程序超时并没有异常弹出,而且电脑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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2008-01-29 LINQ体验(6)——LINQ语句之Join和Order By(转)