praeclarum / sqlite-net

Simple, powerful, cross-platform SQLite client and ORM for .NET
MIT License
4.03k stars 1.42k forks source link

Consider moving LockWrapper to struct #1214

Open mastef opened 6 months ago

mastef commented 6 months ago

Similar to System.Workflow.Runtime.InstanceLockGuard being an IDisposable struct or System.Collection.List having a struct Enumerator the LockWrapper could be a struct.

This way it's instantiated on the stack instead of the heap, and is cleaned up when being Disposed - no GC. Just that in this case Lock() can't return an IDisposable, as that'd box it right back to the heap.

Maybe something like this :

        /// on the returned object.
        /// </summary>
        /// <returns>The lock.</returns>
-       public IDisposable Lock ()
+       public LockWrapper Lock ()
        {
-           return SkipLock ? (IDisposable)new FakeLockWrapper() : new LockWrapper (_lockPoint);
+           return new LockWrapper(SkipLock, SkipLock ? null : _lockPoint);
        }

-       class LockWrapper : IDisposable
+       public readonly struct LockWrapper : IDisposable
        {
-           object _lockPoint;
+           readonly bool _skipLock;
+           readonly object _lockPoint;

-           public LockWrapper (object lockPoint)
+           public LockWrapper (bool skipLock, object lockPoint)
            {
+               _skipLock = skipLock;
                _lockPoint = lockPoint;
+               if (_skipLock) return;
                Monitor.Enter (_lockPoint);
            }

            public void Dispose ()
            {
+               if (_skipLock) return;
                Monitor.Exit (_lockPoint);
            }
        }
-       class FakeLockWrapper : IDisposable
-       {
-           public void Dispose ()
-           {
-           }
-       }
    }
 }