Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Optimistic Locking Implementation in C#

14 min readintermediate
Website QA and SEO audits

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 never takes a lock. You read a record together with a version token (an integer, a timestamp, a SQL Server rowversion, an HTTP ETag), mutate a private copy, then write back with the token in the predicate: UPDATE ... SET v = v + 1 WHERE id = ? AND v = ?. If the affected-row count comes back zero, somebody else wrote first, so you discard your work and retry from a fresh read. The whole design is a bet that conflicts are rare, and the cost of losing the bet is a wasted round trip rather than a stalled thread. That is the opposite trade from mutual exclusion, which pays coordination cost on every access so conflicts become impossible. Two hazards are permanent. The retry loop must be bounded and jittered or contention becomes livelock. And a token that can be reused makes equality a lie: the value went A, then B, then back to A, your check passes, and a change you never observed is silently overwritten. The eight languages diverge because the token lives somewhere different in each. Some hand you a declarative version column in the ORM, some make you count rows off the driver yourself, and in shared memory the primitive is a hardware compare-and-swap whose exact signature, memory ordering rules and spurious-failure behaviour are genuinely different per language.

Optimistic Locking in C#: what you actually reach for

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.

C# implementation

Library code awaits with ConfigureAwait(false) and threads a CancellationToken through every attempt. The concurrency token is exposed as a property the application never assigns. Reviewers prefer ExecuteUpdateAsync over load-modify-SaveChanges when the operation is a pure compare-and-set, want a record for the immutable snapshot, and will reject a catch of DbUpdateConcurrencyException that retries against the same DbContext without reloading, because the change tracker still holds the values that just lost.
csharp
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 Free

The C#-specific 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. 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.

Performance in C#, beyond the O(1)

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. The asymptotic cost is the same in every language, O(1) time and O(1) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Optimistic Locking between languages.

Real-World Applications

Optimistic Locking is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In C#, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Optimistic Locking helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Optimistic Locking appears frequently in onsite coding rounds at mid-to-large tech companies. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Optimistic Locking over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Optimistic Locking to build pattern recognition. In C#, demonstrate proficiency with LINQ and async patterns to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic C# code that is both correct and maintainable.

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).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

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 trial

Studying for this? Replit free tiers and academic plans are laid out on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

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.