Skip to content

There may be unexpectedly high delays in ReaderWriterLockSlim operations #69206

@kouvel

Description

@kouvel

When the spin-lock used by ReaderWriterLockSlim internally is contended, the spin-lock falls back to Thread.Sleep(1) after some spin-waiting. The Sleep(1)s can delay the operation for some or many milliseconds depending on how much contention there is.

Repro:

using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

static class Program
{
    private static void Main(string[] args)
    {
        var rwLock = new ReaderWriterLockSlim();
        Action enterExit = () =>
        {
            var sw = Stopwatch.StartNew();
            rwLock.EnterReadLock();
            rwLock.ExitReadLock();
            double elapsedMs = sw.Elapsed.TotalMilliseconds;
            if (elapsedMs >= 0.5)
            {
                Console.WriteLine($"{elapsedMs,6:0.0} ms");
            }
        };

        var tasks = new Task[100];
        while (true)
        {
            for (int i = 0; i < 100; ++i)
            {
                tasks[i] = Task.Run(enterExit);
            }

            Task.WaitAll(tasks);
        }
    }
}

Sample output:

   0.9 ms
   1.0 ms
   0.8 ms
   0.7 ms
   1.0 ms
  15.0 ms
  15.0 ms
  15.1 ms
  15.1 ms
  15.1 ms
  15.1 ms
  15.1 ms
  30.6 ms
  30.6 ms
  30.6 ms
  46.4 ms
  14.3 ms
   0.5 ms
   0.5 ms

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions