Last post Jan 06, 2016 06:47 AM by Klein Zhang
Jan 05, 2016 12:30 PM|ssjGanesh|LINK
static readonly SiteStructure _instance = new SiteStructure();This is thread safety but I dnt know how it is...?Can somebody explain me?
Jan 05, 2016 12:43 PM|Mukesh_Kumar|LINK
A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only
once at runtime. Let's understand it practically.
static readonly is typically used if the type of the field is not allowed in a const declaration,
or when the value is not known at compile time.
Instance readonly fields are also allowed.
Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to
the field. It specifically does not make immutable the object pointed to by the reference.
public static readonly Test test = new Test();
static void Main(string args)
test.Name = "Program";
test = new Test(); // Error: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer)
Why Static Readonly
Hope this will help you.
Jan 05, 2016 01:07 PM|PatriceSc|LINK
- _instance is thread safe because readonly allows .NET to handle entirely itself when it is initialized (and according to this link, .NET does this in a thread safe way) and then your own code can't change this value anymore
- note though that it doesn't say anything about SiteStructure members (their thread safety dépends on how they are coded, it is unrelated to the thread safety of _instance)
Jan 06, 2016 06:47 AM|Klein Zhang|LINK
static readonly SiteStructure _instance = new SiteStructure();
This is thread safety but I dnt know how it is...?
You complete code like the following code, isn't it?
public class MyClass
public readonly static MyClass Instance = new MyClass();
NET CLR ensures that static initialization is always thread-safe. No matter how many threads are accessing it and what order, it will always be initialized once. The class initialization is guaranteed by the specification of the C# language to be thread
safe, so only one instance of MyClass will be created. You would have to ensure thread safety from that point onwards yourself.
Besides, this code show signs of the beginnings of a Singleton pattern. Basically if you want to run custom code before you initialize the class, then you need to ensure thread-safety on your own.
This is an example where you would need to make your custom code thread safe. But the static initialization part is always thread safe.