Friday, January 12, 2007

Regex hangs with complicated expressions or long string inputs, the Solution

After some struggles and wondering why my application hangs sometimes without throwing any exceptions or errors in event log entries, I was able to find out that the Regex in .Net was the issue.
so I started investigating and there are some nice handy solutions online but it's little sophsiticated and coupled specifically with regular expressions, while if you use the ThreadPool class, it's much easier to control threads and start asynchronous processes and wait for it a for a certain amount of time until it either finishes or the time is up.

here is all what you need (vb.net 2.0 .net framework)!

Imports System.Threading
'you create a threadnotify object to monitor the asynchronous process
Dim ThreadNotify As AutoResetEvent = New AutoResetEvent(False)
'start the process
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf StartMyAsyncProcess), ThreadNotify)
'wait 1.5 seconds , if the time is over, the thread will halt itself and this program will resume.
ThreadNotify.WaitOne(1500, True)
end sub
'the asynch process
Private Sub StartMyAsyncProcess(ByVal state As Object)
in_string = Regex.Replace(in_string, "\s*\r\n\s*", vbNewLine)
state.set()
End Sub

No comments: