Optimistic Locking Implementation in C#
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Optimistic Locking runs in O(1) time and O(1) space, in C# as in every other language.
- ✓EF Core does it declaratively: [Timestamp] on a byte[] property maps SQL Server's rowversion, or .IsConcurrencyToken() marks any column, and SaveChanges throws DbUpdateConcurrencyException whose Entries expose GetDatabaseValues() for the merge.
- ✓Library code awaits with ConfigureAwait(false) and threads a CancellationToken through every attempt.
- ✓The C# trap: Interlocked.CompareExchange takes (ref location, value, comparand), the new value before the expected one, which is the reverse of nearly every other language's compare-and-set.
- ✓Interlocked lowers to LOCK CMPXCHG, roughly twenty nanoseconds uncontended and a full fence; under contention the cacheline transfer dominates and a plain lock can win.
What Optimistic Locking actually is
Optimistic Locking in C#: what you actually reach for
C# implementation
using Microsoft.EntityFrameworkCore;
// EF Core 7+: ExecuteUpdateAsync emits ONE UPDATE and returns the row count.
// It bypasses the change tracker completely, so a losing attempt leaves no
// stale entity behind -- the trap with SaveChanges + DbUpdateConcurrencyException,
// where the tracked entity keeps re-sending the version you already lost with.
public static async Task<bool> WithdrawAsync(
BankContext ctx, int id, decimal amount, CancellationToken ct = default)
{
for (var attempt = 0; attempt < 5; attempt++)
{
var snap = await ctx.Accounts.AsNoTracking()
.FirstOrDefaultAsync(a => a.Id == id, ct)
.ConfigureAwait(false);
if (snap is null || snap.Balance < amount) return false;
var rows = await ctx.Accounts
.Where(a => a.Id == id && a.Version == snap.Version)
.ExecuteUpdateAsync(s => s
.SetProperty(a => a.Balance, a => a.Balance - amount)
.SetProperty(a => a.Version, a => a.Version + 1), ct)
.ConfigureAwait(false);
if (rows == 1) return true; // we won the race
await Task.Delay(5 << attempt, ct).ConfigureAwait(false);
}
throw new InvalidOperationException("conflict budget exhausted");
}Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe C#-specific trap
Performance in C#, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which C# type or library should I use for Optimistic Locking?
EF Core does it declaratively: [Timestamp] on a byte[] property maps SQL Server's rowversion, or .IsConcurrencyToken() marks any column, and SaveChanges throws DbUpdateConcurrencyException whose Entries expose GetDatabaseValues() for the merge. Since EF Core 7, ExecuteUpdateAsync sends one UPDATE carrying your version predicate and returns the affected row count with no change tracker involved. Raw ADO.NET is SqlCommand.ExecuteNonQuery returning rows affected. In memory, System.Threading.Interlocked.CompareExchange(ref location, value, comparand) returns the original value, and ImmutableInterlocked.Update wraps the entire retry loop for immutable collections.
What is the most common C# mistake when implementing Optimistic Locking?
Interlocked.CompareExchange takes (ref location, value, comparand), the new value before the expected one, which is the reverse of nearly every other language's compare-and-set. Swapping the two arguments compiles cleanly and writes the wrong thing. It returns the original value, so the only correct win test is original == comparand; comparing against the new value also reports success when another thread had already stored that same value. Second, a rowversion is a byte[] and == on it compares references, so use SequenceEqual or a Span<byte> comparison. Third, retrying after DbUpdateConcurrencyException on the same DbContext re-sends the original values held by the tracker. Nullable reference annotations catch none of this, being compile-time only.
How does Optimistic Locking actually perform in C#?
Interlocked lowers to LOCK CMPXCHG, roughly twenty nanoseconds uncontended and a full fence; under contention the cacheline transfer dominates and a plain lock can win. On the data side EF Core's change tracker is the real constant, a few microseconds per tracked entity plus a snapshot allocation, which is why ExecuteUpdateAsync over an AsNoTracking read is measurably cheaper than SaveChanges for a pure compare-and-set. A struct concurrency token avoids the per-row byte[] allocation, and comparing a rowversion through Span<byte> allocates nothing. Every retry is one more round trip, so bound and jitter it. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialStudying for this? Replit free tiers and academic plans are laid out on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.