In a static class, I have a method which will edit a variable. The class is static because the class is about site detaild and so only one instance is ever required.
Anyway, thread synchronisation is required. I have a lock object, but when I make it private it and say lock (obj){} I get all sorts of errors.
Why is not possible to make the lock object private?
One thought, do you initialise the object statically. Try declaring:
private static object lockObject = new object();
It should work. Are you declaring it as private static?
private static readonly object lockObject = new object();
public static void Method() {
lock(lockObject) {
// ...
}
}
Related
How can I write the following code in one line?
private static LockSDP instance;
private static readonly object _lock = new();
public static LockSDP GetInstance
{
get
{
if (instance is null) lock (_lock) instance ??= new();
return instance;
}
}
not everything can be one line; however, this can perhaps be easier; you could use Lazy<T>, but for a simple static here where you're mostly after deferred instantiation, I would probably lean on static field behaviour and a nested class:
public static LockSDP GetInstance => LockProxy.Instance;
private static class LockProxy { public static readonly LockSDP Instance = new(); }
I'd probably prefer Marc's answer but just so it's there:
private static readonly Lazy<LockSDP> _lazyInstance =
new Lazy<LockSDP>(() => new LockSDP()); // Default is Threadsafe access.
public static LockSDP Instance => _lazyInstance.Value;
And yes: I do realize it is still 2 lines :/
For reference: Lazy<T>
What if, I replaced private constructor with a static constructor in singleton Design pattern?
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Static constructor will be called only once and I couldn't find any difference in the implementation. Can we replace private with static constructor?
All that the private constructor is really doing in this case is preventing anything outside of the class from instantiating an instance of class Singleton, which is almost certainly intentional as a singleton should only have a single instance.
Static class constructors are run once for a type, at an unknown time, before the type, or any of it's static members, is to be utilized. Static fields are initialized before the static constructor would be run.
So, I suppose you could replace the constructor with a static one, but that would then give you the implicit parameter-less constructor on the Singleton Type, which would allow anyone to instantiate an instance, which is likely at odds with why you are using the singleton pattern in the first place. It also wouldn't change anything about how your class was being constructed, really, so why do it?
Take the following class as an example:
public class Test { }
Under the covers, because there is no declared constructor, the C# compiler implicitly adds a parameterless, public constructor to the class, allowing consumers to create an instance.
public class Program {
public static void Main() {
var test = new Test();
}
}
This is all fine and good if you want to be able to make instances of your class. The singleton pattern intends to only provide a single instance of a type to the consumers. We could add this static instance to our test type like so:
public class Test { public static Test Instance {get;} = new Test(); }
and we would be able to get this static instance like so:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // less than ideal
}
}
So we are providing access to our singleton object through it's instance field, as expected, but we can still create instances of the singleton type, which is less good, as it goes against the purpose of a singleton (namely, having only a single shared instance.)
So we add a private, parameterless constructor to the type.
public class Test {
private Test() {}
public static Test Instance {get;} = new Test();
}
Adding a constructor to a type will cause the C# compiler not to add an implicit public parameter-less constructor. Making it private allows it to be accessed within the class scope, which is used for instantiating our instance property, and prevents anything else from instantiating the object. The end result being:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // Compile time error
}
}
Your singleton object now prevents other instances of the class from being instantiated, and the only way to use it is through the instance property as intended.
In simple terms, if you remove the private constructor, then anyone will be able to create a new instance of Singleton:
// With the private constructor, the compiler will prevent this code from working.
// Without it, the code becomes legal.
var newInstance = new Singleton();
And if anyone can instantiate Singleton as above, then you no longer have a singleton.
Another cleaner way to do it is to use readonly on you private instance.
This is less code and also thread safe. The CLR takes care of everything for you, no need for lock , check for null and stuff.
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance {
get {
return _instance;
}
}
private Singleton()
{
}
}
Then simply test:
[TestMethod]
public void IsSingleton()
{
Assert.AreSame(Singleton.Instance, Singleton.Instance);
}
EDIT:
example using lock
public sealed class Singleton
{
private static readonly object _lock = new object();
private static Singleton instance = new Singleton();
public static Singleton Instance
{
get
{
lock(_lock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
private Singleton()
{
}
}
In simplest terms, if you remove private, the default public constructor will get exposed. Then outsiders will be allowed to use new Singleton(); and make number of instances of Singleton class. So no Singleton Pattern will be there.
Additionally this classic implementation of Singleton pattern (private constructor + static getInstance() with either lazy-loading or eager loading) is so evil. In modern day you must switch to a Dependency-Injection framework instead.
This should work just fine. You could also make the class static and generic so you can store whatever kind of value in instance you want it to hold. This would facilitate the separation of concerns, keeping the singleton pattern and the class that it will contain separate.
I have a sample static class
public static class SampleClass
{
private static readonly string _personName;
private static readonly string _country;
static SampleClass()
{
_personName = "JourneyMan";
_country = "Zee";
System.Threading.Thread.Sleep(5000);
}
public static string PersonName
{
get { return _personName; }
}
public static string Country
{
get { return _country; }
}
}
I have deliberately introduced a Thread.Sleep in the static constructor.
I wrote a sample application in which two threads wait on a ManualResetEvent. I tried to simulate the scenario where one thread tries to query a property and is executing the static constructor and is put to sleep, can the other thread access the second property and return null value?
But according to what I observed, the second thread cannot fetch the property value unless the construction is complete.
Is this handled for us? or am I doing something wrong?
So can I assume, in the above case, there is no lock needed to ensure construction of static class is complete?
Thanks
The static constructor is thread safe, static properties no.
Static constructors are guaranteed to be run only once per application
domain, before any instances of a class are created or any static
members are accessed.
http://msdn.microsoft.com/en-us/library/aa645612.aspx
You should be thread safe in this example. Based on the Static Constructors documentation a static constructor 'is called automatically before the first instance is created or any static members are referenced', so it should be impossible to reference the members before the constructor has completed.
I have a situation where, for testing, I only want my timer method (FooMethod) to run one at a time. In the example below, FooMethod is passed as the delegate to a timer. There are many concrete instances of this class. I thought that by making _locker static, only one instance of FooMethod() would process at a time. But when I run the app, multiple threads are getting past the TryEnter() line at a time.
This is how I'm adding each class to a new timer. This is done, in a loop, for each foo instance:
_timers.Add(new Timer(foo.FooMethod, null, 0, 10000));
And this is the class that has that method:
public class Foo<T>
{
private static readonly object _locker = new object();
public void FooMethod(object stateInfo)
{
// Don't let threads back up; just get out
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}
Note: Normally, _locker isn't static; I don't want the same thread entering the method before it got a chance to complete. I changed it to static here for testing.
My first thought is that maybe this isn't working because the class is generic? And that each concrete class is actually its own class and they don't share the _locker variable? Is that true? If that's true how should I have the concrete classes share a _locker variable? Do I need to add a static _locker variable to some other class to which the Foos have access?
Do I need to add a static _locker variable to some other class to
which the Foos have access?
Yes.
Each closed Foo<T> type, with different T arguments, has its own static _locker object. You could make Foo inherit from a base class, and put the static object there. Then, all the types would use the same instance.
Maybe
public class Foo
{
protected static readonly object _locker = new object();
}
public class Foo<T> : Foo
{
public void FooMethod(object stateInfo)
{
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}
You are correct. Each unique type T referenced in code causes the CLR to generate a new concrete type for Foo<T> and each has its own set of static members.
You could restructure your code to look like the following. It is but one among many valid variations.
public class Foo
{
private static readonly object _locker = new object();
public void FooMethod(object stateInfo)
{
// Don't let threads back up; just get out
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}
public class Foo<T>
{
public void FooMethod(object stateInfo)
{
Foo.FooMethod(stateInfo);
}
}
Also, keep in mind that you can start the timer with an infinite period to prevent the callback from executing more than once. Call Change again at the end of FooMethod to queue the timer again. Since you have multiple timers all going at once you will still have multiple concurrent executions of FooMethod going simultaneously, but at least now there will only be one active call per timer. That is not exactly what you asked for, but I thought I would point this out anyway.
_timers.Add(new Timer(foo.FooMethod, _timers.Count, 10000, Timeout.Infinite));
public class Foo<T>
{
public void FooMethod(object stateInfo)
{
try
{
// Logic here
}
finally
{
int index = (int)stateInfo;
_timers[index].Change(10000, Timeout.Infinite);
}
}
}
Please make this class as non-generic type. That would purpose your need.
public class Foo
{
private static readonly object _locker = new object();
public void FooMethod(object stateInfo)
{
// Don't let threads back up; just get out
if (!Monitor.TryEnter(_locker)) { return; }
try
{
// Logic here
}
finally
{
Monitor.Exit(_locker);
}
}
}
it may be basic question
to have a singleton in multi-threaded environment we can use a lock. Please refer the code snippet. But why do we need double-checked locking in singleton pattern? And more what does double-checked locking means?
class singleton
{
private static singleton instance = null;
private static singleton() { }
private static object objectlock = new object();
public static singleton Instance
{
get
{
lock (objectlock) //single - check lock
{
if (instance == null)
{
instance = new singleton();
}
return instance;
}
}
}
}
Jon Skeet explains this in detail.
Locks are expensive.
If the object already exists, there's no point in taking out a lock.
Thus, you have a first check outside the lock.
However, even if the object didn't exist before you took the look, another thread may have created it between the if condition and the lock statement.
Therefore, you need to check again inside the lock.
However, the best way to write a singleton is to use a static constructor:
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
And with .Net 4.x and newer you should defer to the Lazy class when possible as this pattern is used with the Initialization And Publication option. (note: the inverse is available as well where creation isn't thread safe but the publication of the instance is via the Publication option)
Multithreaded Singleton : The best approach to use double check locking
public sealed class Singleton
{
private static volatile Singleton _instance;
private static readonly object InstanceLoker= new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (_instance == null)
{
lock (InstanceLoker)
{
if (_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
}
}
The "best" way I know is this:
public class MySingleton {
// object for synchronization
private static readonly object syncRoot = new object();
// the singleton instance
private static MySingleton #default;
public static MySingleton Default {
get {
// geting singleton instance without locking
var result = #default;
// if result is NOT null, no additional action is required
if ( object.ReferenceEquals(result, null) ){
// lock the synchronization object
lock(syncRoot) {
// geting singleton instanc in lock - because
// the value of #default field could be changed
result = #default;
// checking for NULL
if ( object.ReferenceEquals(result, null) ) {
// if result is NULL, create new singleton instance
result = new MySingleton();
// set the default instance
#default = result;
}
}
}
// return singleton instance
return result;
}
}
}
If you create the object in the field initialiser, you don't need the lock:
class singleton
{
private static singleton instance = new singleton();
private static singleton() { }
public static singleton Instance
{
get { return instance; }
}
}
Also - bear in mind that the lock is only controlling the creation of the object, the object would still need to be thread-safe if you're using it in multiple threads.
When we try to execute the method of the singleton class using Parallel libraries. It doesn’t recognize the singleton behavior because of multi threading is executing in TPL which causes to failure of concept Singleton Pattern . To overcome this problem there is concept of the locking of the object so that at a time only one thread can access it.
But this is not efficient approach because involvement of lock checking creates unnecessary watches to the object. To avoid it we make use “Double locking checking”