From 5f4731ee24aa008dacc30e9765fa524f2cbb82a7 Mon Sep 17 00:00:00 2001 From: Anairkoen Schno Date: Tue, 28 Jan 2020 12:19:54 -0600 Subject: [PATCH] Added general scope guard utility --- IPA.Loader/Utilities/Utils.cs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/IPA.Loader/Utilities/Utils.cs b/IPA.Loader/Utilities/Utils.cs index 3f6ced24..3b756c2e 100644 --- a/IPA.Loader/Utilities/Utils.cs +++ b/IPA.Loader/Utilities/Utils.cs @@ -190,6 +190,40 @@ namespace IPA.Utilities return cmpVal; } + /// + /// An object used to manage scope guards. + /// + /// + /// + /// using var _ = new Utils.ScopeGuardObject(() => RunOnScopeExit(value)); + /// + /// + /// + public struct ScopeGuardObject : IDisposable + { + private readonly Action action; + /// + /// Creates a new scope guard that will invoke when disposed. + /// + /// the action to run on dispose + public ScopeGuardObject(Action action) + => this.action = action; + void IDisposable.Dispose() + => action?.Invoke(); + } + + /// + /// Creates a scope guard for a given . + /// + /// teh to run on dispose + /// a that will run on disposal + /// + /// + /// using var _ = Utils.ScopeGuard(() => RunOnScopeExit(value)); + /// + /// + public static ScopeGuardObject ScopeGuard(Action action) + => new ScopeGuardObject(action); internal static bool HasInterface(this TypeDefinition type, string interfaceFullName) {