From de94d788e9a47432a7630a8215896b8dd3628599 Mon Sep 17 00:00:00 2001 From: vnugent Date: Sun, 8 Jan 2023 16:01:54 -0500 Subject: Reorder + analyzer cleanup --- lib/Utils/src/VnDisposeable.cs | 85 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 lib/Utils/src/VnDisposeable.cs (limited to 'lib/Utils/src/VnDisposeable.cs') diff --git a/lib/Utils/src/VnDisposeable.cs b/lib/Utils/src/VnDisposeable.cs new file mode 100644 index 0000000..4230a13 --- /dev/null +++ b/lib/Utils/src/VnDisposeable.cs @@ -0,0 +1,85 @@ +/* +* Copyright (c) 2022 Vaughn Nugent +* +* Library: VNLib +* Package: VNLib.Utils +* File: VnDisposeable.cs +* +* VnDisposeable.cs is part of VNLib.Utils which is part of the larger +* VNLib collection of libraries and utilities. +* +* VNLib.Utils is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published +* by the Free Software Foundation, either version 2 of the License, +* or (at your option) any later version. +* +* VNLib.Utils is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +* General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with VNLib.Utils. If not, see http://www.gnu.org/licenses/. +*/ + +using System; +using System.Runtime.CompilerServices; + +namespace VNLib.Utils +{ + /// + /// Provides a base class with abstract methods for for disposable objects, with disposed check method + /// + public abstract class VnDisposeable : IDisposable + { + /// + protected bool Disposed { get; private set; } + + /// + /// When overriden in a child class, is responsible for freeing resources + /// + protected abstract void Free(); + + /// + /// Checks if the current object has been disposed. Method will be inlined where possible + /// + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected virtual void Check() + { + if (Disposed) + { + throw new ObjectDisposedException("Object has been disposed"); + } + } + + /// + /// Sets the internal state to diposed without calling operation. + /// Usefull if another code-path performs the free operation independant of a dispose opreation. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + protected void SetDisposedState() => Disposed = true; + /// + protected virtual void Dispose(bool disposing) + { + if (!Disposed) + { + if (disposing) + { + //Call free method + Free(); + } + Disposed = true; + } + } + //Finalizer is not needed here + + /// + public void Dispose() + { + // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method + Dispose(disposing: true); + GC.SuppressFinalize(this); + } + } +} \ No newline at end of file -- cgit