Assume a class SomeClass with private static field like this. The access to this field is synchronized using lock.
private static SomeClass _instance
private static object _sync = new object();
public static SomeClass Instance
{
get
{
lock (_sync)
{
if (_instance == null)
{
_instance = Create();
}
return _instance;
}
}
}
When another code from different thread will try to set the value of this variable to e.g. null using reflection, will the lock prevent this and let the reflection call wait until the lock was released?
E.g. something like this:
Type type = typeof(SomeClass);
string fieldName = "_instance";
object value = null;
FieldInfo field = type.GetField(fieldName, true);
field.SetValue(null, value);
No, lock will not prevent any access that does not go through locking the same resource. Since reflection will not go through lock, you will get race conditions.
Here is (slightly different from your code but nontheless doing same thing) what I mean→
void SetOne(){
lock (_sync){
critical_element = SOME_VALUE;
}
}
void SetTwo(){
critical_element = SOME_ANOTHER_VALUE;
}
Above definitely has race conditions.
Here is my understanding behind the OP's question. I think OP wants to use Singleton pattern and here is a very nice and thread safe implementation. You do not need to deal with locks either. However, some bad users might still set the backing field using reflection.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy = new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton(){}
}
Related
public class FileStorage
{
private static FileStorage _instance;
public static FileStorage instance
{
get
{
return (_instance != null) ? _instance : _instance = new FileStorage();
}
}
//public string GetAddress...
}
can i use that piece of code for a simple singleton solution? the code will execute on single thread.
Does the return, return a new FileStorage()?
what does exactly be returned here?
var foo = (bee = new[]{/*immagination...*/})
will foo be a boolean value? or effectively it's a reference to bee?
Yes, this would work as you intended. However, even if you are working with a single-threaded application, keep in mind that this method is not thread-safe.
Still, to avoid going on a bug hunt when you need to use threads in your app, it is usually better to ensure thread safety precautionarily.
For example:
public class FileStorage
{
private static readonly object _singletonLock = new object();
private static FileStorage _instance = null;
public static FileStorage Instance
{
get
{
lock (_singletonLock)
{
return _instance ??= new FileStorage();
}
}
}
}
This code snippet makes use of the ??= operator (assign if null) and also encapsulates the getter method of the Instance property in a lock-statement to ensure thread safety.
??= is much more compact and easier to read and has the same effect as your ternary operator.
Im trying to test my singleton object in C# but somehow not satisfied on how I brute force instantiating the object(using parallel foreach).
Is there a right way/better way to test it?
I don't understand what you mean with "parallel foreach". A singleton is implemented like this:
public class MyClass
{
private static MyClass _instance;
private MyClass()
{
//Do Stuff
}
public static MyClass GetInstance()
{
if(_instance == null)
_instance = new MyClass();
return _instance;
}
}
Another way, instead of a Method is a Property:
private static readonly object LockObject = new object();
private static MyClass _instance;
public static MyClass Instance
{
get
{
lock (LockObject)
{
return _instance ?? (_instance = new MyClass());
}
}
}
While I prefer the first Method, cause it's much easier to implement, even for beginners, the Property is also a good way
Singleton class can have only one instance, If it is initialized multiple times then that means you have not correctly implemented the Singleton Design.
You can check the instance.Hashcode() value, it must remain same wherever you are using the instance of that Singleton class.
I have a C# static class accessed from multiple threads. Two questions:
Are my private static fields thread safe when the field is initialized on declaration?
Should I lock when creating private static fields from within static constructor?
Usage of static class from different threads:
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
Task.Run(() =>
{
string name = MyStaticClass.GetValue(9555);
//...
});
}
}
}
Option 1 of static class:
public static class MyStaticClass
{
private static MyClass _myClass = new MyClass();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Option 2 of static class:
public static class MyStaticClass
{
private static MyClass _myClass;
private static object _lockObj = new object();
static MyStaticClass()
{
InitMyClass();
}
private static void InitMyClass()
{
if (_myClass == null)
{
lock(_lockObj)
{
if (_myClass == null)
{
_myClass = new MyClass();
}
}
}
}
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Instance class created from the static class:
public class MyClass
{
private Dictionary<int, Guid> _valuesDict = new Dictionary<int, Guid>();
public MyClass()
{
for (int i = 0; i < 10000; i++)
{
_valuesDict.Add(i, Guid.NewGuid());
}
}
public string GetValue(int key)
{
if (_valuesDict.TryGetValue(key, out Guid value))
{
return value.ToString();
}
return string.Empty;
}
}
Should I lock when initializing private static fields from within static constructor?
Let's not bury the lede here:
Never lock in a static constructor. Static constructors are already locked by the framework so that they run on one thread exactly once.
This is a special case of a more general bit of good advice: never do anything fancy with threads in a static constructor. The fact that static constructors are effectively locked, and that lock can be contested by any code that accesses your type, means that you can very quickly get into deadlocks that you did not expect and are hard to see. I give an example here: https://ericlippert.com/2013/01/31/the-no-lock-deadlock/
If you want lazy initialization, use the Lazy<T> construct; it was written by experts who know how to make it safe.
Are my private static fields thread safe when the field is initialized on declaration?
Thread safety is the preservation of program invariants when program elements are called from multiple threads. You haven't said what your invariants are, so it is impossible to say if your program is "safe".
If the invariant you are worried about is that the static constructor is observed to run before the first static method is executed, or the first instance is created, of a type, C# guarantees that. Of course, if you write crazy code in your static constructor, then crazy things can happen, so again, try to keep your static constructors very simple.
fields of static class are not thread safe by default and should avoid unless it is just for read purpose.
Here down side is "lock" as well, it will create serialized processing in multi threaded environment.
public static class MyStaticClass
{
private static MyClass _myClass;
private static object _lockObj;
static MyStaticClass()
{
_myClass = new MyClass();
_lockObj = new object();
}
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
public static void SetValue(int key)
{
lock(_lockObj)
{
_myClass.SetValue(key);
}
}
}
Your second version is preferable. You can lock it down a little bit more by making your field readonly:
public static class MyStaticClass
{
private static readonly MyClass _myClass = new MyClass();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
}
Your intent appears to be that _myClass is initially set to an instance of MyClass and never set to another. readonly accomplishes that by specifying that it can only be set once, either in a static constructor or by initializing it as above. Not only can another thread not set it, but any attempt to change it will result in a compiler error.
You could omit readonly and just never set _myClass again, but readonly both communicates and enforces your intent.
Here's where it gets trickier: Your reference to an instance of MyClass is thread safe. You don't have to worry about whether various threads will replace it with a different instance (or set it to null), and it will be instantiated before any threads attempt to interact with it.
What this does not do is make MyClass thread safe. Without knowing what it does or how you interact with it, there's no way for me to say what the needs or concerns are.
If that is a concern, one approach is to use a lock to prevent concurrent access that shouldn't occur, exactly as #Mahi1722 demonstrated. I'm including the code from that answer (not to plagiarize, but if anything happens to that answer then this one will refer to an answer that doesn't exist.)
public static class MyStaticClass
{
private static MyClass _myClass = new MyClass();
private static object _lockObj = new object();
public static string GetValue(int key)
{
return _myClass.GetValue(key);
}
public static void SetValue(int key)
{
lock(_lockObj)
{
_myClass.SetValue(key);
}
}
}
Both methods that interact with _myClass lock using _lockObject which means that any execution of either will block while another thread is executing either.
That's a valid approach. Another is to actually make MyClass thread safe, either by using concurrent collections or implementing such locks within that class. That way you don't have to use lock statements in every class that uses an instance of MyClass. You can just use it knowing that it manages that internally.
Both are correct,
but there is no need to lock inside static constructor.
So, i will choose the first option, it is shorter and clearer
I have a singleton defined like this:
public partial class MoonDataManager
{
static MoonDataManager _singletonInstance;
public static MoonDataManager SingletonInstance
{
get
{
return _singletonInstance;
}
private set
{
_singletonInstance = value;
}
}
I have a function that safely creates the instance:
public static async Task<MoonDataManager> CreateSingletonAsync()
{
_singletonInstance = new MoonDataManager();
Should I:
return _singletonInstance; (field)
or
return SingletonInstance; (property)
I'm concerned with Garbage Collection, especially in iOS or Android within Xamarin.
Also if there are naming patterns for this in C# let me know if I deviated from a standard.
Update:
Now I think I really got myself stuck with threading and async methods. Here are the objects and their goals:
MoonDataManager : Run the RegisterTable<Models.IssuerKey> once per table. This is a generic method that essentially runs (new MobileServiceSQLiteStore).DefineTable<T>()
OfflineStore : This is a MobileServiceSQLiteStore.
MobileClient : This is a MobileServiceClient.
MoonDataManager Dependencies: The MoonDataManager requires OfflineStore and MobileClient to finish initialization. Specifically, it does a MobileServiceClient.SyncContext.InitializeAsync(OfflineStore)
I'm not sure how to make sense of this spaghetti of dependencies... or how to make the code look nice, and be thread safe.
Here is the new iteration of the code:
private readonly Lazy<MobileServiceClient> lazyMobileClient =
new Lazy<MobileServiceClient>(() => new MobileServiceClient(Constants.ApplicationURL), true); // true for thread safety
public MobileServiceClient MobileClient { get { return lazyMobileClient.Value; } }
private readonly Lazy< MobileServiceSQLiteStore> offlineDB =
new Lazy<MobileServiceSQLiteStore>(() => new MobileServiceSQLiteStore(Constants.OfflineDBName), true ); // true for thread safety
private MobileServiceSQLiteStore OfflineStore { get { return offlineDB.Value; } }
private static readonly Lazy<MoonDataManager> lazy = new Lazy<MoonDataManager>(() => new MoonDataManager(), true); // true for thread safety
public static MoonDataManager Instance { get { return lazy.Value; } }
private MoonDataManager()
{
MoonDataManager.Instance.RegisterTable<Models.IssuerKey>();
// Initialize file sync
// todo: investigate FileSyncTriggerFactory overload.
//Was present on Mar 30, 2016 Channel9 https://channel9.msdn.com/events/Build/2016/P408
MoonDataManager.Instance.MobileClient.InitializeFileSyncContext
(new IssuerKeyFileSyncHandler(Instance), Instance.OfflineStore);
// NOTE THE ASYNC METHOD HERE (won't compile)
await MoonDataManager.Instance.MobileClient
.SyncContext.InitializeAsync(MoonDataManager.Instance.OfflineStore,
StoreTrackingOptions.NotifyLocalAndServerOperations);
}
For .NET 4 or higher, you can use the Lazy<T> and create it like this.
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton(), true); // true for thread safety
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
It will be created only if it is accessed and only the first time and it is threadsafe.
The definition
static MoonDataManager _singletonInstance;
ensures that the instance of MoonDataManager is a GC root, and it will not be collected until the application domain ends, because it is a static value.
I'd return the private singleton and forego the auto property that you have.
public partial class MoonDataManager
{
private static readonly Lazy<MoonDataManager> _manager =
new Lazy<MoonDataManager>(() => new MoonDataManager());
public static MoonDataManager SingletonInstance => _manager.Value;
}
When MoonDataManager.Value is accessed for the first time, it is initialized using the Func<MoonDataManager> that was passed to the constructor for Lazy<T>. On subsequent accesses, the same instance is returned.
A Singleton creates itself the first time it's accessed, in a way that ensures only one instance will get created, even if a second thread tries to access it while it's still being instantiated
your CreateSingletonAsync() violates this, and looks like it'd allow for multi-thread nastiness
You want something like:
public static MoonDataManager SingletonInstance
{
get
{
if (_singletonInsatnce != null)
return _singletonInstance;
lock (lockobject)
{
// check for null again, as new one may have been created while a thread was waiting on the lock
if (_singletonInsatnce != null)
return _singletonInstance;
else
// create new one here.
}
}
// no setter, because by definition no other class can instantiate the singleton
}
All this is just to ensure that two threads asking for one object don't end up creating two objects, or the second thread getting a half-created object if the first thread's one is still being created.
NB: Singletons have become unfashionable.
NB: If you can be sure that you've got time to create your object before it's ever accessed, you can just use a static member and create it on application start.
Your question "should I return the property or field" doesn't make sense -- you're already returning the field from the property getter, which is standard practise. Where else are you wanting to return something?
You should return the private instance. You can read more about the singleton pattern on MSDN. The standard singleton implementation is as follows:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Although, normally, you don't have a setter for the property. This pattern has already previously been discussed on SO.
What is the difference (if any) between using
void MethodName()
{
lock(this)
{
// (...)
}
}
or
private object o = new object();
void MethodName()
{
lock(o)
{
// (...)
}
}
?
Is there a difference in performance? Style? Behaviour?
lock(this) will lock on the "current" object.
Locking on "this" is usually a bad idea as it exposes the lock to other code; I prefer to have a readonly field, like this:
public class Foo
{
private readonly object padlock = new object();
public void SomeMethod()
{
lock(padlock)
{
...
}
}
}
That way all calls to SomeMethod (and anything else in Foo which locks on padlock) will lock on the same monitor for the same instance of Foo, but nothing else can interfere by locking on that monitor.
In reality, unless you're dealing with "rogue" code, it's unlikely that other code will actually lock on the reference to an instance of Foo, but it's a matter of encapsulation.
The difference is that anyone can lock on your instance, but only you can lock on a private object.
This helps prevent deadlocks.
For example:
Let's say that Microsoft used lock(this) in the Control class.
Then, if someone else locks on a Control instance, his lock would prevent the code in Control from running, which is not what he wants.
This is particularly bad if you lock on types that are shared across AppDomains
The pattern I usually follow is this, for a class declared static....
public static class SomeClass{
private static object objLock = new object();
....
public static object SomeProperty{
get{
lock(objLock){
// Do whatever needs to be done
}
}
set{
lock(objLock){
}
}
}
}
Likewise for a normal class I would follow this pattern:
public class SomeClass{
private readonly object objLock = new object();
....
public object SomeProperty{
get{
lock(objLock){
// Do whatever needs to be done
}
}
set{
lock(objLock){
}
}
}
}
In that way, no one can lock on my instance and will prevent deadlocks from occuring...
Edit: I have amended this article to make it clearer with regards to the code where the basis of the static lock would be used and for a normal class... Thanks Steven and Dalle for their point outs...
There is a difference in scope and there can be a difference in behavior
(incidentally, using "this" is not recommended by MS
// in this case, your lock object is public, so classes outside of this can lock on the same thing
lock(this) {}
// in this case, your lock is private, and only you can issue a lock statement against it
private object lockobj = new object()
..
lock(this.lockobj) {}
// this one is WRONG -- you willget a new object instance every time, so your lock will not provide mutual exclusion
void SomeMethod()
{
// using a local variable for a lock -- wrong
object obj = new object();
lock(obj) {}
}