lock(this) in singleton pattern - c#

Is using lock(this) instead of lock(lockObject) good implementation in a singleton lazy multi thread implementation?
example:
public class MedicineHelper
{
private static MedicineHelper medicineHelper;
private MedicineHelper()
{
}
public static MedicineHelper GetInstance()
{
if (medicineHelper == null)
{
lock (this)
{
if (medicineHelper == null) medicineHelper = new MedicineHelper();
}
}
return medicineHelper;
}
}
The classical pattern require a lock dedicated object like this:
public class MedicineHelper
{
private static MedicineHelper medicineHelper;
private static Object lockObject = new Object();
private MedicineHelper()
{
}
public static MedicineHelper GetInstance()
{
if (medicineHelper == null)
{
lock (LockObject)
{
if (medicineHelper == null) medicineHelper = new MedicineHelper();
}
}
return medicineHelper;
}
}

It is not a good implementation because you can't do it. "this" is not available from a static method.

Related

Is there a way to populate a base class singleton instance with a derived class?

I have a base player class, which contains a Singleton declaration. I want to populate the baseClass.Instance var with derivedClass, if at all possible.
My current approach is that, when the derivedClass "wakes up," it attempts to set Instance = this; I have also tried calling base.Init(), then setting Instance = this; within the base.Init() method. This sets Instance != null, but Instance != derivedClass either.
// Current approach
public abstract class BasePlayer : Entity, IPlayerBase
{
// Singleton instance, to be populated by the derived class
private static BasePlayer _i = null;
private static object _lock = new object();
private static bool _disposing = false; // Check if we're in the process of disposing this singleton
public static BasePlayer Instance
{
get
{
if (_disposing)
return null;
else
return _i;
}
protected set
{
lock (_lock)
{
if(_i == null && !_disposing)
_i = value;
}
}
}
protected void Init()
{
if (Instance == null)
{
Instance = this;
}
else if (Instance != null)
{
Active = false;
Destroy(this.gameObject);
}
if (Instance == this)
{
Debug.Log("Successfully set BaseClass");
...
}
}
}
// Current approach
public class FPSPlayer : BasePlayer
{
void OnEnable()
{
base.Init();
}
}
// Also tried
public class FPSPlayer : BasePlayer
{
void OnEnable()
{
if (Instance == null)
{
Instance = this;
}
else if (Instance != null)
{
Active = false;
Destroy(this.gameObject);
}
if (Instance == this)
{
...
}
}
}
Use a factory class to return your singleton instance. e.g.
public static class PlayerFactory
{
private static BasePlayer _instance;
public static BasePlayer Instance
{
get { return _instance; }
protected set { _instance = value; }
}
}
which should accept any object descended from BasePlayer as the single instance.

Would it be possible to inject service into singleton class c#

I wonder what would be correct way to inject services into singleton class (by using NInject framework, for example.
What singleton code is doing actually - it run windows form in application context
public class FrontController
{
private static volatile FrontController _instance;
private static readonly object syncRoot = new Object();
private ControlsContainer _controlsContainer;
private FrontController() { }
public static FrontController Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
if (_instance == null)
{
_instance = new FrontController();
}
}
}
return _instance;
}
}
public void StartApplication()
{
_controlsContainer = new ControlsContainer();
Application.Run(_controlsContainer);
}
public void EndApplication()
{
//throw new NotImplementedException();
}
internal void Synchronize()
{
ISymantecService<ClientModel> service =
new SymantecService<ClientModel>(new CustomerRepository<ClientModel>());
service.Synchronize();
}
}
We have
public void StartApplication()
{
_controlsContainer = new ControlsContainer();
Application.Run(_controlsContainer);
}
as well as
internal void Synchronize()
{
ISymantecService<ClientModel> service =
new SymantecService<ClientModel>(new CustomerRepository<ClientModel>());
quickBookservice.Synchronize();
}
Is there any way to inject ISymantecService and ICustomerRepository in this class in a thread safe manner.

Thread synchronization with multiple methods

I have a static class with multiple static methods.
private static Session _session = new Session();
public static void Method1() {
if(_session != null)
_session.Action();
}
public static void Method2() {
if(_session != null)
_session.Action();
}
public static void Method3() {
if(_session != null)
_session.Action();
}
public static void Method4(string path) {
_session.Disconnect();
_session.Connect(new Config(path));
}
Method1, Method2, Method3 are fully thread safe, they can be safely called simultaneously from any number of threads. In fact, for performance reasons, I need to allow multiple threads to call Method1,2,3 concurrently.
The problem is, it is possible for Method1,2,3 to throw an exception when Method4() is being called.
How do I allow multiple threads to call Method1,2,3 while also blocking them when Method4() is being called?
As SLaks has pointed out, a ReadWriterLock was a great solution.
Here is what I ended up implementing:
private static ReaderWriterLockSlim _lock = new ReaderWriterLockSlim();
private static Session _session = new Session();
public static void Method1() {
_lock.EnterReadLock();
try {
if(_session != null)
_session.Action();
}
finally
{
_lock.ExitReadLock();
}
}
public static void Method2() {
_lock.EnterReadLock();
try {
if(_session != null)
_session.Action();
}
finally
{
_lock.ExitReadLock();
}
}
public static void Method3() {
_lock.EnterReadLock();
try {
if(_session != null)
_session.Action();
}
finally
{
_lock.ExitReadLock();
}
}
public static void Method4(string path) {
_lock.EnterWriteLock();
try {
if(_session != null)
_session.Action();
}
finally
{
_lock.ExitWriteLock();
}
}
Great performance, no threading issues!
private static RefCountDisposable _refCountDisposible = new RefCountDisposable();
private static Session _session = new Session();
public Constructor()
{
_refCountDisposible = new RefCountDisposable(
Disposible.Create(() => _session.Disconnect()));
}
public static void Method1() {
using(_refCountDisposible.GetDisposible())
if(_session != null)
_session.Action();
}
public static void Method2() {
using(_refCountDisposible.GetDisposible())
if(_session != null)
_session.Action();
}
public static void Method3() {
using(_refCountDisposible.GetDisposible())
if(_session != null)
_session.Action();
}
public static void Method4(string path) {
_refCountDisposible.Dispose()
}
How about ManualResetEvent?
M4()
{
_event.Reset();
try
//reconnect
finally
_event.Set();
}
M1,2,3()
{
_event.WaitOne();
//do actions
}

Deallocate and re-instantiate new a singleton

I want to de-allocate the memory from the original singleton object and create a new one with another method.
public sealed class ObjectZ {
static readonly ObjectZ _instance = new ObjectZ();
private ObjectZ() {}
public static ObjectZ Instance{
get { return _instance; }
}
}
What would this method look like?
Singletons are usually created once and exist for the lifetime of the domain, recreating a singleton is dodgy business and by definition the code I've provided isn't truly a singleton.
The behaviour you seem to be after is a statically accessible single object cache that can be invalidated.
public static class SingletonAccessor
{
private static SomeClass _instance;
private static object _lock = new Object();
public static SomeClass Singleton
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new SomeClass();
}
return _instance;
}
}
}
public static void Recycle()
{
lock (_lock)
{
if (_instance != null)
{
// Do any cleanup, perhaps call .Dispose if it's needed
_instance = null;
}
}
}
}

WeakReference - Am I doing it right?

I have a static class, which exposes a event:
public static class MyStaticClass
{
static bool myBool= false;
public static bool MyBool
{
get { return myBool; }
private set
{
myBool= value;
var handler = MyBoolChanged;
if (handler != null)
handler(null, null);
}
}
public static event EventHandler MyBoolChanged;
}
And then I am registering to it using this pattern:
class AnotherClass
{
WeakReference _me;
public MyMethodInAnotherClass()
{
_me = new WeakReference(this);
MyStaticClass.MyBoolChanged+=
(_me.Target as AnotherClass).MyMethodInAnotherClassCallback;
}
private void MyMethodInAnotherClassCallback(some arguments)
{
}
}
What I want to achieve is that MyStaticClass will only execute the handler if the instance of AnotherClass has not been disposed (and has not deregistered).
The best way I can see to use this is to forget about an event, and use some kind of list instead; let's say List<WeakReference>; you could then have:
interface IFoo {
void Bar(some args);
}
with:
static class Whatever {
private static readonly List<WeakReference> items=new List<WeakReference>();
public static void Add(IFoo foo) {
if(foo != null) {
var newRef = new WeakReference(foo);
lock(items) { items.Add(newRef); }
}
}
public static void DoIt(some args) {
lock(items) {
foreach(var item in items) {
IFoo foo = item.IsAlive ? item.Target as IFoo : null;
if(foo != null) foo.Bar(some args);
}
}
}
}
with additional mechanisms to remove a specific IFoo, and to remove all dead foos left todo.
Then you just need AnotherClass : IFoo, with a Bar() implementation that applies your callback.
Additional emphasis: static collections (including events) are fairly dangerous; you must have some kind of sweep occasionally to remove empty items, and try to unsubscribe promptly where possible (in Dispose(), for example). As an illustration:
public static void Remove(IFoo foo) {
lock (items) { // also remove any dead debris
items.RemoveAll(x => !x.IsAlive || x.Target == foo || x.Target == null);
}
}

Categories

Resources