Skip to content

Repository files navigation

logo

NuGet StatusMIT LicenseCIRelease

Simplistic, atomic, interlocked counter that spreads writes across per-thread shards so concurrent updates do not all contend on a single shared value.

Why this exists

ShardedCounter is optimized for write-heavy concurrent scenarios. Each thread writes to its own shard, and reads compute the current total by summing the shard values.

This tradeoff is useful when:

  • many threads are updating the counter frequently
  • reads are less frequent than writes
  • a single Interlocked value becomes a hotspot under contention

Installation

dotnet add package ShardedCounter

Usage

usingShardedCounter.Core;varcounter=newShardedCounter();counter.Add(5);counter.Add(-2);counter.Increment();counter.Decrement();Console.WriteLine(counter.Count);// 3

Public API

publicclassShardedCounter{publicvoidAdd(longamount);publicvoidIncrease(longamount);publicvoidDecrease(longamount);publicvoidIncrement();publicvoidDecrement();publiclongCount{get;}}

Add(long amount) is the recommended API because it makes signed counter updates explicit. Increase and Decrease remain available as convenience and compatibility methods.

Target frameworks

The library currently targets:

  • net6.0
  • net8.0

Notes

  • Writes are cheap because they stay on a thread-local shard.
  • Reads are more expensive because they sum all known shards.
  • This library is best suited to counters that are updated often and read occasionally.

Validation

  • Unit tests cover signed updates, compatibility APIs, and concurrent writer scenarios.
  • The benchmark project compares ShardedCounter against a plain Interlocked counter under multiple thread counts.

Run the benchmarks with:

dotnet run -c Release --project ShardedCounter.Core.Benchmarks

BenchmarkDotNet will emit markdown and other result artifacts under BenchmarkDotNet.Artifacts/. If you want benchmark snapshots in the repo, rerun the benchmark project intentionally and check in the generated markdown summary you want to preserve.

Releases

About

🎰 Simplistic, atomic, interlocked counter that allows for huge numbers of operations to be performed using a "sharding" style approach to summation, all in .NET Core C#

Topics

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages