October 18, 2026 · .NET · C# · Thread Safety
Shared mutable state in .NET, explained with a counter and a string
What shared mutable state is, why it matters, the issues it can cause, and how to prevent them.
It’s been a while since I’ve written. About two weeks I think. Thankfully I have some free time this weekend so I wanted to write something short on shared mutable state, why it matters, the potential issues, and how we can prevent those issues.
I will mostly talk about it here and give a very simplified idea on the topic, so please take a look at my GitHub repository to see the full examples based off of what I talk about. The code for this post can be found in these places:
Services/SharedMutableStateService.cs, to see the service implementation- The
Models/Staticfolder, to see the static and non-static class examples Controllers/SharedMutableStateController.cs, to see the usages
One thing to keep in mind: the code in this post is simplified. The repository has full working examples, so some details differ. For example, I left out the comments and some of the supporting methods here. The concepts are exactly the same.
What is shared mutable state?
Let’s first define what each word means in “shared mutable state” to understand what it means when an application feature introduces this risk:
- Shared: The class instance or class property has exactly one copy or location per program, making it accessible across different execution threads (like concurrent HTTP requests).
- Mutable: The data inside that property or instance can be changed or overwritten after it has been created.
- State: The actual value or information stored in memory at any given moment.
So, when we say a component has a shared mutable state, we mean there is only one single instance of that data globally available to the entire program, it is actively shared across all incoming HTTP requests, and any thread can change its value.
In modern web frameworks like .NET, we usually create shared mutable state in two ways:
1. Registering a service dependency as a Singleton.
// See the dependency injection post for more details
builder.Services.AddSingleton<ISingletonCounterService, SingletonCounterService>();2. Using the static keyword on a class property or field.
public static class StaticClass
{
public static int Count { get; set; } = 0;
public static string Name { get; set; } = string.Empty;
}
public class NonStaticClass
{
public static int Count { get; set; } = 0;
public string Name { get; set; } = string.Empty;
} Let’s focus on the static keyword since singletons through Dependency Injection (DI) have already been covered in another post.
Static classes vs. static properties
I want to focus on where we use the static keyword in both of these classes. In StaticClass we use it in the class modifier and in the property values, whereas in NonStaticClass we only use it on Count. What implications does this have?
Well, when a class is marked as static, it means that all of its members need to be static as well. As a matter of fact, not marking all of its contents as static will throw a compiler error. A static class can’t be instantiated at all, so its members exist once for the entire application.
However, if you only want a property to be static and not the entire class, then the only thing that needs to be static is the property itself. In NonStaticClass we can see that Count is static, but Name is not. So how will this behave? Every time you create a new instance of NonStaticClass, the class itself will be a fresh copy, but Count will be shared across every single copy that is ever created.
One thing that I feel needs to be addressed and might be a bit confusing for some individuals: how can a string be considered to have a shared mutable state when a string itself is immutable? Well, the string object itself never changes, but the field holding it does. Every time the string is “updated,” a brand new string is created and the field is changed to point to it. Since every thread can read and write that field, the state is still shared and mutable.
The race condition
There’s a problem that can arise from creating shared and static properties: what if two people try to update a value at the same time? Let’s assume we try to increase Count from either of our classes with Count++;. Some individuals may think that this gets done by simply adding 1 to the count blindly, but that would be wrong. It actually takes 3 steps to add 1 to the count:
- Read
Count. - Add one to the value.
- Write the new value to the heap.
What happens when two or more people try to increase the value at overlapping moments? Well, both could read the same value, add one to it, and then write their own result to the heap. This is what we call a race condition. Essentially, whoever writes last to the heap will have their value persist. This is obviously an issue because if the count is 50 and person 1 writes 51 and person 2 writes 51, then the count is off by 1. The threads don’t need to start at the exact same instant, they only need to overlap at the wrong moment, so this is not rare at all, especially if the API is receiving thousands of requests per second.
Seeing it in action
Let’s take a look at an example that I wrote to help demonstrate this. I wanted to show the static keyword above so we could see the difference between static classes and static properties, but the demo itself uses a singleton service. It behaves the same way for our purposes: there is only one shared instance, so every thread reads and writes the same fields. Here is the service interface:
public interface ISharedMutableStateService
{
Task ResetCountAsync();
Task<int> GetCountAsync();
Task AddToCountNotThreadSafeAsync();
Task AddToCountThreadSafeAsync();
Task ResetStrAsync();
Task<string> GetStr();
Task WriteStringNotThreadSafeAsync(string str);
Task WriteStringThreadSafeAsync(string str);
}The two methods I want to focus on are these:
public Task AddToCountNotThreadSafeAsync()
{
_count++;
return Task.CompletedTask;
}
public Task WriteStringNotThreadSafeAsync(string str)
{
_str += str;
return Task.CompletedTask;
}As you can guess from the method names, they are not thread safe. To prove this, I simulated thousands of concurrent calls to the service and logged the results. The counter variable is simply added by one and the string is reassigned to include the provided string. I then printed the total count and the length of the string, plus their respective expected values.
I did not print out the expected characters in order because the tasks run concurrently, which meant that I had no control over the order in which they would execute, so doing an “expected string” and an “actual string” would look wrong at first glance even if thread safe. It’s definitely not a bug and it is expected. The main point is to see if there are lost values or not.
private const string CharacterPool = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
private const int IterationCount = 10000;
[HttpGet]
public async Task<IActionResult> AddToCountNotThreadSafe()
{
await sharedMutableStateService.ResetCountAsync();
var tasks = new List<Task>();
for (var i = 0; i < IterationCount; i++)
{
tasks.Add(Task.Run(sharedMutableStateService.AddToCountNotThreadSafeAsync));
}
Console.WriteLine($"Method: {nameof(AddToCountNotThreadSafe)} - Expected Count: {IterationCount}");
await Task.WhenAll(tasks);
Console.WriteLine($"Method: {nameof(AddToCountNotThreadSafe)} - Actual Count: {await sharedMutableStateService.GetCountAsync()}");
return Ok();
}
[HttpGet]
public async Task<IActionResult> WriteStringNotThreadSafe()
{
await sharedMutableStateService.ResetStrAsync();
var strBuilder = new StringBuilder();
var tasks = new List<Task>();
for (var i = 0; i < IterationCount; i++)
{
var character = Random.Shared.GetItems<char>(CharacterPool, 1)[0].ToString();
strBuilder.Append(character);
tasks.Add(Task.Run(() => sharedMutableStateService.WriteStringNotThreadSafeAsync(character)));
}
Console.WriteLine($"Method: {nameof(WriteStringNotThreadSafe)} - Expected Character Count: {strBuilder.ToString().Length}");
await Task.WhenAll(tasks);
var actualString = await sharedMutableStateService.GetStr();
Console.WriteLine($"Method: {nameof(WriteStringNotThreadSafe)} - Actual Character Count: {actualString.Length}");
return Ok();
}Method: AddToCountNotThreadSafe - Expected Count: 10000
Method: AddToCountNotThreadSafe - Actual Count: 9759
Method: WriteStringNotThreadSafe - Expected Character Count: 10000
Method: WriteStringNotThreadSafe - Actual Character Count: 3501As you can see, there are missing counts and missing characters. Your exact numbers will be different on every run, since they depend on how the threads happen to overlap, but you should see lost values each time you try it.
Fixing it
So how do we keep those issues from occurring? We make sure only one thread can update the value at a time.
private int _count;
private readonly Lock _strLock = new();
private string _str = string.Empty;
public Task AddToCountThreadSafeAsync()
{
Interlocked.Increment(ref _count);
return Task.CompletedTask;
}
public Task WriteStringThreadSafeAsync(string str)
{
lock (_strLock)
{
_str += str;
}
return Task.CompletedTask;
} You might have noticed that there are two ways to do it: using Interlocked and using a lock. Interlocked is preferred on simple data types as it is much faster and lightweight than a regular lock, but a lock works on all data types.
Running the same tests, except with thread safety in mind, we get the following results:
Method: AddToCountThreadSafe - Expected Count: 10000
Method: AddToCountThreadSafe - Actual Count: 10000
Method: WriteStringThreadSafe - Expected Character Count: 10000
Method: WriteStringThreadSafe - Actual Character Count: 10000As you can see, no count loss or data loss as our updates are protected.
Where you’d use it
Where would we implement these though? Here are some scenarios where you could implement a shared mutable state object:
- In-memory caching and state management: If you are building a custom cache to store configuration data or reference lists globally, you’ll use a singleton dictionary or class. When multiple requests try to refresh or fetch cache data simultaneously, utilizing a lock prevents “cache stampede” issues where multiple threads duplicate the same database queries.
- Application telemetry and custom counters: If you need to keep an eye on your application’s health or other metrics—like tracking the number of active WebSocket connections, counting failed login attempts, or logging how many times a specific critical background worker runs—a singleton service backed by
Interlocked.Incrementgives you a very fast, low-overhead tracking tool. - Rate-limiting middleware: When protecting your API from brute-force attacks or scraping, you need a way to track how many requests an IP address or user ID has made within a short window. Storing these counts in a shared global dictionary allows your middleware to safely and rapidly check and update request tallies across all incoming concurrent HTTP connections.
The takeaway
That’s shared mutable state in a very simplified way. It allows you to track mutable properties and objects throughout your application, whether it be in a static property and/or class or a singleton service through dependency injection. Just remember that anything shared and mutable needs to be protected.