Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to create a static Regex object to be used by all threads in an ASP.NET application?

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.

like image 493
Karim Avatar asked Nov 02 '09 22:11

Karim


People also ask

Is regex thread safe C#?

The Regex class itself is thread safe and immutable (read-only).

Why static is not thread safe?

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.

Are static properties thread safe C#?

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.

What is the most accurate description of a regular expression C#?

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.


2 Answers

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!

like image 80
Jon Skeet Avatar answered Oct 09 '22 15:10

Jon Skeet


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.

like image 37
sentece Avatar answered Oct 09 '22 13:10

sentece