I need to know if it's safe to create a static Regex object like this:
public static Regex s_Regex_ExtractEmails = new Regex(@"\b[A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,4}\b");
And call it statically from ASP.NET threads like this:
s_Regex_ExtractEmails.Matches("my email is [email protected]")
Would this cause any problems?
I am doing this basically as an optimization so that the Regex object can be precompiled and reused.
The Regex class itself is thread safe and immutable (read-only).
Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process. Hence, access to static variable is not thread safe.
Static constructors are always thread safe. The runtime guarantees that a static constructor is only called once. So even if a type is called by multiple threads at the same time, the static constructor is always executed one time.
In C#, Regular Expression is a pattern which is used to parse and check whether the given input text is matching with the given pattern or not.
Yes, Regex
objects are thread-safe. From the docs:
The Regex class is immutable (read-only) and is inherently thread safe. Regex objects can be created on any thread and shared between threads.
You might want to consider using RegexOptions.Compiled
too - although don't assume it'll help performance; measure!
I used a static Regex in a web app and it turned out to be a bottleneck as all requests used the same single instance.
I rewrote the function so a new Regex was created for each call and problem solved.
The app may have run faster at low usage levels but at very high levels of usage it didn't scale well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With