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

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


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.


Not only safe, it is recommended to use it like this when you can. This approach will improve the performance of your application.