When you use regular matching to compare large data, the program time-out does not eject abnormally, and the computer CPU reaches 100%
In. Net4.5 Microsoft has improved methods, direct invocation is very convenient, but. Net4.5 below it, write down the way you find it.
1,. In Net4.5:
Regex reg = new Regex (regular, Regexoptions.ignorecase, Timespan.fromseconds (2));
Timespan.fromseconds is the set timeout time, such as the return is empty, fromseconds=2 is seconds, you can set the Minutes hours
2,. In Net4.0:
1 /// <summary>2 ///Regular parsing3 /// </summary>4 /// <param name= "regex" >Regular Objects</param>5 /// <param name= "Input" >the string to parse</param>6 /// <param name= "Outtimemilliseconds" >Timeout period</param>7 /// <returns></returns>8 Public StaticMatchCollection matchs (Regex regex,stringInputintouttimemilliseconds)9 {TenMatchCollection MC =NULL; OneAutoResetEvent is =NewAutoResetEvent (false); AThread T =NewThread (Delegate() - { -MC =regex. Matches (input); the //Note that it is important to traverse all the matches here once, otherwise, if you traverse outside of this method. Wait conditions may also occur - foreach(Match minchMC) {} - Is . Set (); - }); + T.start (); -Wait (t, Timespan.frommilliseconds (Outtimemilliseconds), is,NULL); + returnMC; A } at - /// <summary> - ///wait for method execution to complete, or time out - /// </summary> - /// <param name= "T" ></param> - /// <param name= "Outtime" ></param> in /// <param name= "Ares" ></param> - Private Static voidWait (Thread t, TimeSpan Outtime, WaitHandle is, WaitHandle CancelEvent) to { + waithandle[] Ares; - if(CancelEvent = =NULL) theAres =Newwaithandle[] {is}; * Else $Ares =Newwaithandle[] {is, cancelevent};Panax Notoginseng intindex =WaitHandle.WaitAny (Ares, outtime); - if(Index! =0) && t.isalive)//if the signal is not executed, and the thread is still executing, end the thread the { + T.abort (); At =NULL; the } + } - $ /// <summary> $ ///Regular parsing - /// </summary> - /// <param name= "regex" >Regular Objects</param> the /// <param name= "Input" >the string to parse</param> - /// <param name= "Outtimemilliseconds" >Timeout period</param>Wuyi /// <returns></returns> the Public StaticMatch match (Regex regex,stringInputintouttimemilliseconds) - { WuMatch m =NULL; -AutoResetEvent is =NewAutoResetEvent (false); AboutThread T =NewThread (Delegate() {m =regex. Match (input); Is. Set (); }); $ T.start (); -Wait (t, Timespan.frommilliseconds (Outtimemilliseconds), is,NULL); - returnm; -}
View Code
Regular Match timeout processing