Static class constructor which is called once per thread - c#

I'm looking for static class constructor which is called once per thread. Something like this :
class MyClass
{
[ThreadStatic] // This is not working with a method of course.
static MyClass()
{
}
}
What is the best way to achieve it ?

I would use the ThreadLocal class for this. It's similar to using the ThreadStatic keyword, but is much more convenient to use when you need to have initialization code per thread, as seems to be your case.
So if you have:
public class MyClass
{
public MyClass()
{
// normal constructor, with normal initialization code here.
}
}
Wherever you are interested in having a separate instance of MyClass per thread, you can do the following:
ThreadLocal<MyClass> threadSpecificMyClass = new ThreadLocal<MyClass>(() => new MyClass());
You can then share threadSpecificMyClass between multiple threads, but they will all get different instances when invoking threadSpecificMyClass.Value. And you don't have to worry about checking for null, because the initialization happens automatically.

Can't you create a (static) property and assign a new instance to it? Then make the property Threadstatic?

Related

Can we create more than 1 instance using Private Constructor?

We all know that we cannot create object of class having private constructor. So the question arises is how many instances of this class can be created .Please find a sample code below.
public class Test
{
public int val ;
private Test(int sent)
{
val=val +sent;
}
public static void Callme(int GetVal)
{
Test obj=new Test(GetVal);
Console.WriteLine(obj.val);
}
}
public class Program
{
public static void Main()
{
Test.Callme(10);
//Console.WriteLine(Test.val);
Test.Callme(20);
//Console.WriteLine(Test.val);
}
}
As per what I know It should create 2 object of the class. Need help understanding this.
We all know that we cannot create object of class having private constructor.
Well, that's not accurate. You can create an object (instance) of a class having only private constructors by using static members of that class, just like in the code in the question.
What you can't do is create an instances of that class from anywhere else in the code.
how many instances of this class can be created
In your code sample there are two instances of class Test.
I think what might be confusing you is you expected the second Console.WriteLine to print 30, but it printed 20. That is because public int val ; is an instance member. If it was a static member, than it would have printed 30
Maybe something like this is what you're looking for:
public static Test Callme(int GetVal)
{
Test obj = new Test(GetVal);
Console.WriteLine(obj.val);
return obj;
}
And then create new instances like:
Test test1 = Test.Callme(10);
Test test2 = Test.Callme(20);
This way you can easily access the members of each instance. E.g. test1.val
Callme method is a static method. Static methods does not require an objects instance to be called upon. They don't have the this (keyword) reference and can be called directly on the class. In your situation Test.CallMe(someValue). Note that there is no object instance involved here.
If CallMe was NOT a static method you would have needed an instance/object to call it. For example
Test ob = new Test();
ob.CallMe(someValue);
What your example illustrates is the use of private fields/methods.
When a method like the constructor or a filed is marked with the private keyword that method/field can only be called/accessed from within the declaring class.
This means that CallMe can access the constructor because CallMe is a member of the class and the constructor is a member of the class thus they both can access each other.
When a class has only one constructor and that constructor is private it effectively means that an instance of the class can only be created from within the class.
So in current example CallMe creates an instance of the class each time it's called.
If you call CallMe 2 times you'll create 2 instances of the class.
Because the method Callme is static it is instantiated by the system at some point before it is used and then remains in memory for future calls. There is only one copy of a static memeber of a class ever created regardless of how many instances of the class are created.

I think I need a static class with a constructor?

So, apologies in advance for the surely poor terminology in this question - I'm trying to teach myself C#, and struggling with a few concepts.
In pseudo-code, I have something like this:
static void Main()
{
// This will create lots of "Item"(s), and do stuff with them
}
public class Item
{
// a bunch of properties
public Item()
{
}
}
Next, I need a UtilityFunction1 that'll do some work - it will be called many times during Main() and passed Items to do some calculations with them. This function needs to set up a Dictionary to do its job. Even though it will be called many times, the Dictionary should only be set up once.
I also need a UtilityFunction2. Like UtilityFunction1, this function also needs a Dictionary to do it's job, which should only be set up once. This function will be called many times by UtilityFunction1.
So, on one hand, it seems like UtilityFunction1 and UtilityFunction2 should be public classes, since they need to have a constructor that populates the Dictionary (which involves variables, looping, and calculations).
On the other hand, I only need one of UtilityFunction1 and UtilityFunction2, so it seems like they should be static methods. But if that's the case, how/when do they do the work to set up the Dictionaries they need?
How do you achieve this?
You could also move your logic outside of Main.
What forces you to use static is that Main method (and class it's part of, usually) is static. That forces all other things (fields, methods, events, you name it) to also be static. The easiest way of curing that headache would be to create new class to hold all things you need.
Create new Logic class and put all things in it. The Item class stays the same. you can move it to separate file for clarity.
Logic.cs:
public class Logic() {
private Dictionary<object,object> dict1 = new Dictionary<object,object>
private Dictionary<object,object> dict2 = new Dictionary<object,object>
public Logic() {
// some logical initializations here
}
private void UtilityFunction1 (Item itemToWorkOn) {
// you can access dict1 directly from here
}
private void UtilityFunction2 (Item itemToWorkOn) {
// you can access dict2 directly from here
}
public void Run() {
// run UtilityFunction1() many times
// run UtilityFunction2() many times
}
}
Item.cs:
public class Item() {
// a bunch of properties
public Item() {}
}
And then just run it in your Main.
Program.cs:
static class Program {
static void Main() {
new Logic.Run();
}
}
Maybe you can think of the Singelton Design Pattern for your UtilityFunction*
https://msdn.microsoft.com/en-us/library/ff650316.aspx
You need a class that has only one instance, and you need to provide a global point of access to the instance.
You may use a static constructor. A static constructor is guaranteed to be executed just once for the class and before the class is used for the very first time. A static constructor is a very good place for initialization of static properties. It may look like:
public class ExampleClass
{
public static readonly IDictionary<int, Item> Items;
static ExampleClass()
{
Items = new Dictionary<int, Item>();
}
}
However, be careful with static stuff as it usually decreases the modularity and testability of a program. Therefore the use of a singleton pattern might be a better solution rather than a static constructor.

Thread - safe singelton

I have a class which has 3 static members. Each of static member is not thread-safe singleton.
I need to provide a thread safe implementation for their use.Is it ok?Or I need to provide thread-safe wrapper for each of them? If I should - how can I do it using Lazy<T>?
Additional question : Measure() and Do() of SingeltonClass1/2/3 are not thread-safe is func1() thread-safe?
public class MyLazySingleton
{
// static holder for instance, need to use lambda to construct since constructor private
private static readonly Lazy<MyLazySingleton> _instance
= new Lazy<MyLazySingleton>(() => new MyLazySingleton());
// private to prevent direct instantiation.
private MyLazySingleton()
{
s_c1 = SingletonClass1.Instance();
s_c2 = SingletonClass2.Instance();
s_c3 = SingletonClass3.Instance();
}
// accessor for instance
public static MyLazySingletonInstance
{
get
{
return _instance.Value;
}
}
public void func1()
{
if (s_s1.Measure() || s_c2.Measure())
{
c_c3.Do();
}
}
static SingletonClass1 s_c1 = null;
static SingletonClass1 s_c2 = null;
static SingletonClass1 s_c3 = null;
}
How should I re-implement MyLazySingleton if its constructor should get 2 arguments? string str and int i
I have asked a follow up question Thread-safe methods in the singleton class
It's thread-safe as it is.
The default value for Lazy<T>'s LazyThreadSafetyMode is ExecutionAndPublication.
From the MSDN page on the new Lazy<T>(Func<T>) constructor:
An instance that is created with this constructor may be used
concurrently from multiple threads.
The thread safety mode of a Lazy instance that is initialized with
this constructor is LazyThreadSafetyMode.ExecutionAndPublication.
If you were to use another overload where you could pass a different LazyThreadSafetyMode value it wouldn't be thread safe. But using the constructor as you are now, it is thread safe.
EDIT: Regarding your additional edited question, if those methods on your SingletonClass1 type are not thread safe: then no, func1 is not thread safe either.
From the Lazy<T> MSDN Page:
Making the Lazy object thread safe does not protect the lazily
initialized object. If multiple threads can access the lazily
initialized object, you must make its properties and methods safe for
multithreaded access.
You will need to make sure that those methods/interactions between those classes are thread safe. This might be as simple as wrapping the func1 body with a lock statement, but I can't say for certain depending on how your 3 instances of SingletonClass1 interact with each other or how calling code may access them.
To ensure Thread-safety you have to set the LazyThreadSafetyMode parameter of the Lazy<T> constructor. There are 3 available values:
None: not thread-safe
PublicationOnly: many MyLazySingleton instance may be created, but only one will be published/returned by the Value property. Internally it uses Interlocked.CompareExchange
ExecutionAndPublication: The value is create only once
Here's an example:
new Lazy<Test>(() => new Test(), LazyThreadSafetyMode.ExecutionAndPublication)

Lock code section in c#

My question may sound like many others here but it has a flavor I didn't find.
I am trying to understand the following logic
A generic object
public class GenericClass
{
public static void DoSomething(Object lockObj)
{
lock(lockObj)
{
// do something here
}
}
}
Class A
internal class A
{
private static _aLock = new Object();
public void Do_A_Thing()
{
GenericClass.DoSomething(_aLock);
}
}
Class B
internal class B
{
private static _bLock = new Object();
public void Do_B_Thing()
{
GenericClass.DoSomething(_bLock);
}
}
I just hope to confirm if my explanation is correct:
If multiple threads of class "A" will attempt simultaneously access code in "genericClass" method "DoSomething", this method will be locked to all but one instance of class "A". But a single instance of class "B" will be able to proceed with execution any time. If class "B" will also have multiple instances execute, they will not interfere with class "A" locks.
Is this correct based on what you see above?
Yes, your description sounds correct. It is perhaps a little unusual to pass the lock object in, but it'll work fine. The only change I would suggest is to make the static fields readonly so you can't accidentally change the value to a different object reference.
Your conclusion is correct but it is not a good practice to pass locked object around. I suggest to put the lock inside class A and B respectively.
I suggest to write:
internal class A
{
private static readonly _aLock = new Object();
public void Do_A_Thing()
{
lock (_aLock)
{
GenericClass.DoSomething();
}
}
}
Do you have a specific reason to put the lock in another class? Maybe you can solve your problem in a different way?
Also keep in mind that in some conditions, maybe it is not your case, you can have a deadlock if class A and B call each other (A->B->A).
Yes, that is correct. The locks in A and the locks in B are completely unaware of each other. The code will only be blocked when there is another thread locking it with the same object as identifier.
If you are using generics, then something like
public class MyGadget<T>
{
static readonly SyncRoot = new object() ;
public T SynchronizedMethod()
{
lock ( SyncRoot )
{
SynchronizedMethodGuts() ;
}
}
}
should do what you want because MyGadget<Foo> and MyGadget<Bar> are different classes: they each have their own, different SyncRoot field.

Avoiding static variables with Singleton

A colleague of mine told me that I should never use static variables because if you change them in one place, they are changed everywhere. He told me that instead of using static variables I should use Singleton.
I know that Singleton is for limitation of the number of instances of one class to one.
How can Singleton help me with static variables?
Let's address your statements one at a time:
A colleague of mine told me that I should never use static variables because if you change them in one place, they are changed everywhere.
It seems fairly clear that your colleague means the basic feature of static variables: there is only one instance of a static variable. No matter how many instances of any class you create, any access to a static variable is to the same variable. There is not a separate variable for each instance.
He told me that instead of using static variables I should use Singleton.
This is not good global advice. Static variables and singletons aren't in competition with each other and aren't really substitutes for each other. A singleton is an instance of a class, managed in such a way that only one instance is possible to create. A static variable is similarly tied to exactly one (static) instance of a class, but could be assigned with not only a class instance but any data type such as a scalar. In actuality, to effectively use the singleton pattern, you must store it in a static variable. There is no way to "use a singleton instead of a static variable".
On the other hand, perhaps he meant something slightly different: perhaps he was trying to say that instead of your static class having many different static variables, methods, properties, and fields (altogether, members) that function as if they were a class, you should make those fields non-static, and then expose the wrapping class as a Singleton instance. You would still need a private static field with a method or property (or perhaps just use a get-only property) to expose the singleton.
I know that Singleton is for limitation of the number of instances of one class to one. How can Singleton help me with static variables?
A static class's variables and a singleton are alike in that they both are instantiated once (the former enforced by the compiler and the latter enforced by your implementation). The reason you'd want to use a singleton instead of a static variable inside of a class is when your singleton needs to be a true instance of a class, and not consist simply of the collected static members of a static class. This singleton then gets assigned to a static variable so that all callers can acquire a copy of that same instance. As I said above, you can convert all the different static members of your static class to be instance members of your new non-static class which you will expose as a singleton.
I would also like to mention that the other answers given so far all have issues around thread safety. Below are some correct patterns for managing Singletons.
Below, you can see that an instance of the Singleton class, which has instance (or non-static) members, is created either by static initialization or within the static constructor, and is assigned to the variable _singleton.. We use this pattern to ensure that it is instantiated only once. Then, the static method Instance provides read-only access to the backing field variable, which contains our one, and only one, instance of Singleton.
public class Singleton {
// static members
private static readonly Singleton _singleton = new Singleton();
public static Singleton Instance => _singleton
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
or, the exact same thing but with an explicit static constructor:
public class Singleton {
// static members
private static readonly Singleton _singleton; // instead of here, you can...
static Singleton() {
_singleton = new Singleton(); // do it here
}
public static Singleton Instance => _singleton;
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
You could also use a property default without an explicit backing field (below) or in a static constructor can assign the get-only property (not shown).
public class Singleton {
// static members
public static Singleton Instance { get; } = new Singleton();
// instance members
private Singleton() { } // private so no one else can accidentally create an instance
public string Gorp { get; set; }
}
Since static constructors are guaranteed to run exactly once, whether implicit or explicit, then there are no thread safety issues. Note that any access to the Singleton class can trigger static initialization, even reflection-type access.
You can think of static members of a class as almost like a separate, though conjoined, class:
Instance (non-static) members function like a normal class. They don't live until you perform new Class() on them. Each time you do new, you get a new instance. Instance members have access to all static members, including private members (in the same class).
Static members are like members of a separate, special instance of the class that you cannot explicitly create using new. Inside this class, only static members can be accessed or set. There is an implicit or explicit static constructor which .Net runs at the time of first access (just like the class instance, only you don't explicitly create it, it's created when needed). Static members of a class can be accessed by any other class at any time, in or out of an instance, though respecting access modifiers such as internal or private.
EDIT #ErikE's response is the correct approach.
For thread safety, the field should be initialized thusly:
private static readonly Singleton instance = new Singleton();
One way to use a singleton (lifted from http://msdn.microsoft.com/en-us/library/ff650316.aspx)
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
/// non-static members
public string Foo { get; set; }
}
Then,
var foo = Singleton.Instance.Foo;
Singleton.Instance.Foo = "Potential thread collision here.";
Note that the instance member is a static field. You can't implement a singleton without using a static variable, and (I seem to recall - it's been awhile) this instance will be shared across all requests. Because of that, it's inherently not thread safe.
Instead, consider putting these values in a database or other persistent store that's more thread-friendly, and creating a class that interfaces with that portion of your database to provide transparent access.
public static class Foo
{
public static string Bar
{
get { /// retrieve Bar from the db }
set { /// update Bar in the db }
}
}
The whole point of the static modifier is to ensure that the object thus modified is the same wherever it is used as it requires no instantiation. The name originally came about as a static variable has a fixed location in memory and all items referring to it will reference the same memory location.
Now you may wish to use a static field within a class, in which case it exists before the class is instantiated (constructed). There may be instances where you would want this.
A singleton is a different beast. It is a class that is limited to a single instantiation by use of a private constructor and a static property. So in that regard you still can't avoid statics by using a singleton.
To answer the stated question:
It is incredibly stupid (but possible) to create a singleton without a static field.
To do it, you need to use someone else's static field, such as AppDomain.GetData or (in ASP.Net) HttpContext.Application.
Just to answer your question (I hope): Instead of using a static class containing static members like Class1 you can implement the Singleton pattern like in Class2 (please don't begin a discussion about lazy initialization at this point):
public static class Class1
{
public static void DoSomething ()
{
}
}
public static class Class2
{
private Class2() {
}
private Class2 instance;
public Class2 GetInstance(){
if (instance == null)
instance = new Class2();
return instance;
}
public void DoSomething ()
{
}
}
Instead of calling Class1.DoSomething() you can use Class2.GetInstance().DoSomething().
Edit: As you can see there's still a (private) static field inside Class2 holding it's instance.
Edit2 in answer to user966638's comment:
Do I understand you correct that you have code like this:
public class Foo {
private static Bar bar;
}
And your collegue suggests to replace it by this?
public class Foo {
private BarSingleton bar;
}
This could be the case if you want to have different Foo instances where each instance's bar attribute could be set to null for example. But I'm not sure if he meant this what exactly is the use case he is talking about.
Both singleton and static variables give you one instance of a class. Why you should prefer singleton over static is
With Singleton you can manage the lifetime of the instance yourself, they way you want
With Singleton, you have greater control over the initialization of the instance. This useful when initializing an instance of a class is complicated affair.
It's challenging to make static variables thread-safe, with singleton, that task becomes very easy
Hope this helps

Categories