简体   繁体   English

静态类构造函数,每个线程调用一次

[英]Static class constructor which is called once per thread

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. 我将为此使用ThreadLocal类。 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. 这与使用ThreadStatic关键字相似,但是在需要每个线程都有初始化代码的情况下,使用起来更方便,这似乎是您的情况。

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: 如果您希望每个线程有一个单独的MyClass实例,则可以执行以下操作:

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 . 然后,您可以在多个线程之间共享threadSpecificMyClass ,但是在调用threadSpecificMyClass.Value时,它们都将获得不同的实例。 And you don't have to worry about checking for null , because the initialization happens automatically. 而且您不必担心检查null ,因为初始化会自动发生。

Can't you create a (static) property and assign a new instance to it? 您不能创建(静态)属性并为其分配新实例吗? Then make the property Threadstatic? 然后使属性Threadstatic吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM