Singleton instance is always null - c#

I have an ASP.net with MVC program with the current singleton class:
public sealed class Foo
{
private static volatile Foo_instance;
private static object syncRoot = new Object();
private List<Obj> _objList;
private Foo()
{
_objList = new List<Obj>();
}
public static Foo Instance
{
get
{
if (_instance == null)
{
lock (syncRoot)
{
_instance = new Foo();
}
}
return _instance;
}
}
public void AddObjToList(Obj _object)
{
lock (_instance)
{
_objList.Add(_object);
}
}
public void FindAndRemoveObj(string id)
{
lock (_instance)
{
Obj _object = null;
_object= _objList.FirstOrDefault(t => t.UniKey == id);
if (_object!= null)
{
_objList.Remove(object);
}
}
}
}
The first time that a class get the instance of this class it will return a new/clean instace of foo class, as expected, and then populating the list however a second class that will remove itens from the same list is receveing an new instance with an empty list.

This code has the lock in the wrong place:
if (_instance == null)
{
lock (syncRoot)
{
_instance = new Foo();
}
}
As thread 1 creates _instance, a second thread will block on the lock, then create _instance anew when it is released.
Another thing to be careful about it that you should never rely on static variables in IIS across server lookups. The application pool can be recycled at any time.

The conclusion was that the asp.net is creating new instances of the domain and that causes a new singleton object each time. I have searched how to sync objects between domains but that is too "workaround" for me, so I decided to add a boolean column that update the value with the confirmation or failure.
Thanks everyone

Related

Issue in C# singleton with multi threading: a variable not intialized

This is a simplified version of production code and running in multi thread with singleton. Compared to traditional singleton the additional thing is that I initialized client in the lock section.
When I trying to get the client by: Client client = Singleton.Instance.GetClient();, there is chance that client can be null (but the chance is very small).
public class Client
{
public int Value { get; set; } = 10;
}
public class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private Client client = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
// Here is the interesting part!
instance.InitClient();
}
}
}
return instance;
}
}
private void InitClient()
{
this.client = new Client();
}
public Client GetClient()
{
return this.client;
}
}
This is how I testing it:
static void Main(string[] args)
{
Console.WriteLine("Input thread count: ");
int threadCount = Int32.Parse(Console.ReadLine().Trim());
List<Task> tasks = new List<Task>(threadCount);
for (int i = 0; i < threadCount; ++i)
{
tasks.Add(Task.Factory.StartNew(() => DoStuff()));
}
Task.WaitAll(tasks.ToArray());
Console.WriteLine("All threads complete");
}
private static void DoStuff()
{
Client client = Singleton.Instance.GetClient();
if (client.Value != 10)
{
Console.WriteLine($"Thread: {Thread.CurrentThread.ManagedThreadId}.");
}
}
And client can be null in occasionlly:
But when I moved the InitClient() into the private constructor of Singleton, I never meet the situation that client is null:
private Singleton()
{
this.InitClient();
}
I don't have any clue what is difference and what is wrong, thanks for the helping!
As soon as you call instance = new Singleton() inside the lock, "instance" is no longer null, meaning separate (threaded) calls to Singleton.Instance returns immediately, and a call to GetClient on that instance would be a race condition with the InitClient from the first call.
Initializing inside the constructor ensures "Instance" itself is initialized as soon as it's created. So subsequent calls from separate threads wouldn't race against anything.

C# Singleton design pattern basics

Just recently started to try and learn some designs patterns. Currently trying to get my singleton to return a new object. However it keeps throwing the error "Cannot convert method group 'getInstance' to non-delegate type 'MainWdinow.CustomerLoader'. did you intend to invoke the method?
here is the code for the design pattern method
public class CustomerLoader
{
private static Customer firstInstance = null;
public static Customer getInstance()
{
if(firstInstance ==null)
{
firstInstance = new Customer();
}
return firstInstance;
}
}
Here is where I try to call the method and I get the error mentioned above
CustomerLoader t = CustomerLoader.getInstance();
I want my singleton to do the job of the code below and create a new instance of the customer object
Customer T = new Customer;
Use this. It's also thread safe unlike your version
private static readonly Lazy<Customer> _instance = new Lazy<Customer>(() => new Customer());
public static Customer Instance => _instance.Value;
But you should really use dependency injection instead singletons.
And your naming is off, it looks like Java, check this https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members
private members are not covered by guidelines. But even Microsoft uses _camelCase for private fields in corefx https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding-style.md
Use this example:
public class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
Singleton should be about one class, not three.
Be careful with it cause your implementation is not thread-safe. See this padlock variable here. It prevents creating multiple instances in a multi-treaded applicatoins.
CustomerLoader.getInstance
Is a function, you cant assign it to
CustomerLoader
Your code should look more like that:
class Train
{
protected Train() { }
protected static Train instance;
public static Train GetSingeltonInstance()
{
if(instance == null)
{
instance = new Train();
}
return instance;
}
}
class TainUser
{
private readonly Train train;
public TainUser()
{
train = Train.GetSingeltonInstance();
}
}

Will this C# code work in thread-safe mode?

I need to be able to get the Project by ID and safely change the properties of it. I am not the specialist in multi-threading. So, please, help me with this.
public static class Application
{
private static ConcurrentDictionary<string, Project> projects = new ConcurrentDictionary<string, Project>();
private static readonly object locker = new object();
public static Project GetProjectByGuid(string guid)
{
if (guid == null) return null;
lock (locker)
{
return projects.GetValueOrDefault(guid, null);
}
}
public static void AddOrUpdateProject(Project project)
{
Project dbProject;
lock (locker)
{
dbProject = GetProjectByGuid(project.Guid);
if (dbProject == null)
{
projects[project.Guid] = project;
}
}
if (dbProject != null)
{
lock (dbProject.locker)
{
dbProject.Name = project.Name;
dbProject.Users = project.Users;
}
}
}
}
Since the Project object is not thread safe, the answer to your question is no, you will not be able to make this thread safe.

C# singleton instance is never null

I am attempting to implement a singleton pattern in an Azure webjob. Debugging locally the instance is never null. It is always set to the singleton object itself. I feel I'm missing something brutally obvious here.
public sealed class HubErrorList
{
private static volatile HubErrorList instance;
private static object syncRoot = new Object();
private HubErrorList() {}
public static HubErrorList Instance
{
get {
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
{
instance = new HubErrorList();
}
}
}
return instance;
}
}
}
The instance will remain null until the property is accessed. Depending on how you're inspecting this, your tooling may be causing that discrepancy.
That being said, a simpler and nicer "lazy initialized" singleton pattern would be to use Lazy<T> instead:
public sealed class HubErrorList
{
private static Lazy<HubErrorList> instance = new Lazy<HubErrorList>(() => new HubErrorList());
private HubErrorList() {}
public static HubErrorList Instance { get { return instance.Value; } }
}

Locking a thread by user

I need a way to lock c# threads by user
I have my data object and I create new instance for every user.
Every user has several threads that use this object and in I.O. operations I want to lock this object instance for this user only.
Using simple Lock {} is locking all the object instances, there for blocking other user.
I need some simple solution.
Edit
I build new instance of MyDataObj per user;
Then run job that updating some data in MyDataObj every minute;
Using lockObj as lock, lock the data to all the users (Although it's not static Variables)
I need only to lock the data to the current user
this is the code sample
public sealed class MyDataObj
{
private static readonly Dictionary<object, MyDataObj> _instances = new Dictionary<object, MyDataObj>();
public object lockObj = new object();
public bool jobRunning = false;
private string data = string.Empty;
//// --------- constractor -------------------
private MyDataObj(int key)
{
LoadMyDataObj(key);
}
public static MyDataObj GetInstance(int key)
{
lock (_instances)
{
MyDataObj instance;
if (_instances.TryGetValue(key, out instance))
{
instance = _instances[key];
return instance;
}
instance = new MyDataObj(key);
return instance;
}
}
private void LoadMyDataObj(int key)
{
// get the data from db
}
public void UpdateMyData(string newData)
{
lock (lockObj)
{
this.data = newData;
}
}
public string ReadMyData()
{
lock (lockObj)
{
return this.data;
}
}
public class ActionObject
{
MyDataObj myDataObj;
int UserID;
//// --------- constractor -------------------
public ActionObject(int userid)
{
this.UserID = userid;
myDataObj = MyDataObj.GetInstance(userid);
if (!myDataObj.jobRunning)
{
jobs jbs = new jobs(myDataObj);
System.Threading.Thread RunJob = new System.Threading.Thread(new System.Threading.ThreadStart(jbs.dominutesAssignment));
RunJob.Start();
myDataObj.jobRunning = true;
}
}
public ActionObject()
{
myDataObj = MyDataObj.GetInstance(this.UserID);
myDataObj.UpdateMyData("some data");
}
}
public class jobs
{
MyDataObj myDataObj = null;
public jobs(MyDataObj grp)
{
this.myDataObj = grp;
}
public void dominutesAssignment()
{
while (true)
{
myDataObj.ReadMyData();
System.Threading.Thread.Sleep(1000);
}
}
}
}
I need a way to lock c# threads by user. I have my data object and I create new instance for every user
Create one lock per user. Or if the user exists longer than the threads: Use the user object as the lock.
lock (userOrTheUserObject)
{
//Do some op
}
Every user has several threads that use this object and in I.O. operations
That sounds more like you should use asynchronous IO instead of creating several threads (which will be less effecient)
I want to lock this object instance for this user only. Using simple Lock {} is locking all the object instances, there for blocking other user.
If the object is shared between all users you HAVE to lock it using lock. The lock won't be very effective otherwise. The other object is to redesign the object to now be shared.
I need some simple solution.
There are no simple threading solutions.
You can use Monitor. In this sample anyone but user 1 can execute DoIt method concurrently. While user 1 executing DoIt no one can enter it. A weak point is if user 1 tries to execute DoIt when user 2 already executing it, user 2 continues its execution. Also you have to handle exceptions properly otherwise there may be dead locks.
private static readonly object lockObj = new Object();
public void Do(int userId)
{
Monitor.Enter(lockObj);
if (userId != 1)
Monitor.Exit(lockObj);
try
{
DoIt();
}
finally
{
if (userId == 1)
Monitor.Exit(lockObj);
}
}
public void DoIt()
{
// Do It
}

Categories