From ebece1777824328fac4123af052fa1c7dd4183f2 Mon Sep 17 00:00:00 2001 From: "Ilya.Usov" Date: Wed, 15 Jan 2025 14:47:59 +0100 Subject: [PATCH] Log error on accessing non-initialized lifetime to avoid memory leaks. Add `LogErrorIfLifetimeIsNotInitialized` to be able to disable this behaviour --- rd-net/Lifetimes/Lifetimes/Lifetime.cs | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/rd-net/Lifetimes/Lifetimes/Lifetime.cs b/rd-net/Lifetimes/Lifetimes/Lifetime.cs index 187c0c002..5c01e6a3e 100644 --- a/rd-net/Lifetimes/Lifetimes/Lifetime.cs +++ b/rd-net/Lifetimes/Lifetimes/Lifetime.cs @@ -110,14 +110,34 @@ public enum LifetimeTerminationTimeoutKind { private readonly LifetimeDefinition? myDefinition; - internal LifetimeDefinition Definition => myDefinition ?? LifetimeDefinition.Eternal; - + internal LifetimeDefinition Definition + { + get + { + var def = myDefinition; + if (def != null) return def; + + if (LogErrorIfLifetimeIsNotInitialized) + { + Log.Root.Error("Lifetime is not initialized. " + + "This may cause a memory leak as default(Lifetime) is treated as Eternal. " + + "Please provide a properly initialized Lifetime or use `Lifetime?` if you need to handle both cases. " + + "Use Lifetime.Eternal explicitly if that behavior is intended."); + } + + return LifetimeDefinition.Eternal; + } + } + //ctor internal Lifetime(LifetimeDefinition definition) { myDefinition = definition; } + [PublicAPI] + public static bool LogErrorIfLifetimeIsNotInitialized = true; + #if !NET35 ///