Keep a lock’s identity under your control. A string, a publicly accessible object, or a Type can let unrelated code acquire the same gate and delay your operation. A dedicated private gate prevents callers from obtaining that gate through your public API.
This tutorial reproduces that interference with timed attempts, then checks a counter whose gate stays private. The complete console program was compiled and run targeting .NET 10 in a pinned Linux SDK container on November 4, 2026. It uses only the BCL.
Recognize the shared identity
Microsoft’s lock guidelines advise against strings, this, and Type instances. Callers already have a reference to this; another component can obtain the same type object through typeof. An exposed gate property has the same ownership problem.
Strings add a less visible route to sharing. String.Intern returns the same interned reference for equal values. The test explicitly interns two separately constructed strings, so it does not depend on whether this environment automatically interns literals. Equal string contents alone do not establish reference identity.
Run a bounded reproduction and the private-gate fix
Create a .NET 10 console project, replace its entire Program.cs with the program below, and run it:
dotnet new console --framework net10.0 --name LockOwnership
cd LockOwnership
dotnet run
CheckCollision holds one reference while a separate thread tries the other. Monitor.TryEnter uses a 25 millisecond acquisition timeout and reports whether it acquired the monitor. The worker releases it only when acquisition succeeded. The attempt must use a different thread: the owning thread can reenter its own monitor.
Each collision is followed by a successful acquisition after release. Every worker join has a five second assertion bound. These limits detect a failed experiment; they are not real-time scheduling guarantees.
using System;
using System.Threading;
static class Program
{
static void Require(bool condition, string message)
{
if (!condition) throw new InvalidOperationException(message);
}
static void RunWorker(Action work)
{
Exception? failure = null;
var thread = new Thread(() =>
{
try { work(); }
catch (Exception error) { failure = error; }
}) { IsBackground = true };
thread.Start();
Require(thread.Join(5000), "Worker exceeded five seconds.");
if (failure is not null) throw new InvalidOperationException("Worker failed.", failure);
}
static bool CanEnter(object gate)
{
bool taken = false;
try
{
Monitor.TryEnter(gate, 25, ref taken);
return taken;
}
finally
{
if (taken) Monitor.Exit(gate);
}
}
static void CheckCollision(object ownerGate, object otherGate)
{
lock (ownerGate)
{
RunWorker(() => Require(!CanEnter(otherGate), "Expected shared gate contention."));
}
RunWorker(() => Require(CanEnter(otherGate), "Gate remained locked after release."));
}
static void Main()
{
string first = string.Intern(new string("invoice-gate".ToCharArray()));
string second = string.Intern(new string("invoice-gate".ToCharArray()));
Require(ReferenceEquals(first, second), "Interned references should match.");
var exposed = new object();
for (int round = 0; round < 10; round++)
{
CheckCollision(first, second);
CheckCollision(exposed, exposed);
CheckCollision(typeof(Counter), typeof(Counter));
}
Console.WriteLine("Shared string, public object, Type: 10 collisions each; cleanup passed.");
var counter = new Counter();
lock (counter)
{
RunWorker(() => counter.Increment());
}
Require(counter.Value == 1, "External instance lock blocked the private gate.");
using var canceled = new CancellationTokenSource();
canceled.Cancel();
bool cancellationObserved = false;
try { counter.Increment(canceled.Token); }
catch (OperationCanceledException) { cancellationObserved = true; }
Require(cancellationObserved && counter.Value == 1, "Cancellation changed the counter.");
bool faultObserved = false;
try { counter.Increment(fail: true); }
catch (InvalidOperationException) { faultObserved = true; }
Require(faultObserved, "Expected deliberate fault.");
RunWorker(() => counter.Increment());
Require(counter.Value == 2, "Exception left the gate locked.");
Console.WriteLine("Private gate: external lock, cancellation, exception cleanup passed.");
for (int round = 0; round < 10; round++)
{
var start = new ManualResetEventSlim(false);
var workers = new Thread[4];
try
{
for (int index = 0; index < workers.Length; index++)
{
workers[index] = new Thread(() =>
{
if (!start.Wait(5000)) return;
for (int n = 0; n < 1000; n++) counter.Increment();
}) { IsBackground = true };
workers[index].Start();
}
start.Set();
foreach (Thread worker in workers)
Require(worker.Join(5000), "Stress worker exceeded five seconds.");
}
finally
{
start.Set();
// Dispose only after every worker has stopped using the event.
bool stopped = true;
foreach (Thread? worker in workers)
if (worker is not null && !worker.Join(5000)) stopped = false;
if (stopped) start.Dispose();
}
Require(counter.Value == 2 + (round + 1) * 4000, "Lost an increment.");
}
Console.WriteLine("Stress: 10 rounds x 4 workers x 1000 increments = 40000; final value 40002.");
}
}
sealed class Counter
{
private readonly object _gate = new();
private int _value;
public int Value { get { lock (_gate) return _value; } }
public void Increment(CancellationToken token = default, bool fail = false)
{
token.ThrowIfCancellationRequested();
lock (_gate)
{
token.ThrowIfCancellationRequested();
if (fail) throw new InvalidOperationException("Deliberate test fault.");
_value++;
}
}
}
The asserted output is:
Shared string, public object, Type: 10 collisions each; cleanup passed.
Private gate: external lock, cancellation, exception cleanup passed.
Stress: 10 rounds x 4 workers x 1000 increments = 40000; final value 40002.
Read what the assertions establish
The local variable exposed stands in for a gate available through a public API. The first loop checks three accidental sharing routes ten times each: two interned references, one object available to both participants, and two evaluations of the same typeof expression. For an implementation using lock (this), its caller’s reference to the instance supplies that second route. The test demonstrates interference, not a permanent deadlock.
The corrected Counter owns one private readonly object gate and uses it for both reads and writes. Holding lock (counter) no longer prevents a worker from incrementing: the counter instance and its private gate are different objects. The stress loop then checks the exact total after every round, ending at 40,002. That is evidence for this bounded test, not a throughput measurement or proof of every possible schedule.
The cancellation assertion uses an already canceled token and verifies that no increment occurs. The checks before and inside the critical section are cooperative; they do not make waiting for lock cancellable. The deliberate exception occurs inside the gate, and the following worker proves that the gate was released. Microsoft documents the exception cleanup performed by the lock statement.
Apply the ownership rule to your code
Keep one stable gate for the state it protects, use it consistently, and keep it private. Creating a fresh object for every call would give competing operations different gates. Exposing the gate would recreate the interference demonstrated above.
For new code using .NET 9 and C# 13 or later, Microsoft recommends a dedicated System.Threading.Lock. This example deliberately uses an object gate to demonstrate monitor identity and timed monitor acquisition. When adopting the newer type, keep its declared type as System.Threading.Lock so the compiler uses its lock-specific path; see the documented lowering rules.
A private gate does not solve every synchronization problem. If two operations acquire multiple gates in different orders, follow our tested tutorial on fixing two-lock acquisition order. If the failure involves a blocked asynchronous continuation, see diagnosing an async deadlock caused by blocking.