c# - Singleton management implementation and thread safety -
i have been playing around ways implement singletons. have written little management object allows easier, less code approach writing singleton classes.
i never use in production system couple of reason lead me question.
with below code - assuming implementation would/could lead both threading issues , memory leaks? correct?
namespace consoleapplication1 { public static class singletonmanager { private static readonly dictionary<string, object> objects; static singletonmanager() { objects = new dictionary<string, object>(); } public static t instanceof<t>(object[] ctorargs = null) t : class { var name = typeof (t).fullname; if (objects.containskey(name)) return objects[name] t; var ctor = typeof (t).getconstructors( bindingflags.instance | bindingflags.nonpublic)[0]; var instance = ctor.invoke(ctorargs) t; objects[name] = instance; return instance t; } public static void disposeof<t>() t : singleton<t> { dispose(typeof (t).fullname); } public static void disposeof(type type) { dispose(type.fullname); } private static void dispose(string name) { if (!objects.containskey(name)) return; var obj = objects[name]; if (obj idisposable) ((idisposable) objects[name]).dispose(); objects.remove(name); } } public class singleton<t> t : class { private static object threadlock = new object(); public static t instance(object[] ctorargs = null) { lock (threadlock) { return singletonmanager.instanceof<t>(ctorargs); } } } public class somesingletonclass : singleton<somesingletonclass> { public int number; private somesingletonclass(int i) { number = i; } } internal class program { private static void main(string[] args) { var instance1= somesingletonclass.instance(new object[] {1}); var instance2 = somesingletonclass.instance(new object[] { 2 }); //is false var updated = instance1.number == 2; instance2.number = 99; //is true var equals = instance1.number == instance2.number; //is true var refequals = referenceequals(instance1, instance2); debugger.break(); } } }
classical singletons idea. in cases you're better off creating single instance pass code needs it, instead of enforcing there one. ioc container of work you.
an implementation of classical singleton quite compact, no need simplify further:
public class mysingleton { private static lazy<mysingleton> _instance = new lazy<mysingleton>(() => new mysingleton()); public static mysingleton instance { { return _instance.value; } } private mysingleton() { } }
at best can save 2 of these lines.
yes, code not thread safe. you'd need put of in
lock
statements fix that.the consumer determining constructor parameters dubious. unless of them identical, you'll end different instances, depending on consumer runs first.
this violates "single source of truth" principle , maintenance , debugging nightmare.
- your code relies on private reflection.
Comments
Post a Comment