Reputation: 1096
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 ?
Upvotes: 0
Views: 156
Reputation: 36513
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.
Upvotes: 3
Reputation: 3654
Can't you create a (static) property and assign a new instance to it? Then make the property Threadstatic?
Upvotes: 1