Thread Local Storage For C# Class Library

后端 未结 4 1729
不思量自难忘°
不思量自难忘° 2021-01-04 08:06

I have a very old but very large library which I am considering converting to a C# class library. The existing library uses a lot of global variables stored in the TLS. C# h

4条回答
  •  无人及你
    2021-01-04 08:11

    Presuming you're going to use .NET 4.0, you could have a static ThreadLocal where your ThreadLocalData class has all your variables as properties:

    class ThreadLocalData
    {
        public int GlobalInt { get; set; }
        public string GlobalString { get; set; }
    }
    
    class Global
    {
        static ThreadLocal _ThreadLocal =
            new ThreadLocal( () => new ThreadLocalData() );
    
        public static ThreadLocalData ThreadLocal
        {
           get { return _ThreadLocal.Value; }
        }
    }
    

    You would then access the properties like this:

    int i = Global.ThreadLocal.GlobalInt;
    

    You could add any global variables that are not thread-local as normal properties of the Global class.

提交回复
热议问题