实现线程内同一对象

       刚刚换公司,来到新公司后经历了一个星期的适应后正式开始干活。今天为同事解决了一个问题。问题的描述是这样的:首先程序是多线程的,要求就是对单线程内某一对象的访问,必须保证其对象在线程的生命周期内必须是同一个实例,线程是在thread pool中的,也就是说thread不会自己结束。

       因为已经2年没写.net程序了,所以上来有点生疏。依稀记得有一个特性可以搞定!同事让我过去看一下,一看上面写的是ThreadStatic,依稀记得是它。但是不太确定。然同事写着:

[ThreadStatic]
        static test obj = new test();

查了一下msdn,发现ThreadStatic这个属性是可以实现,但是不能声明+初始化对象放在一起,搞了半天,决定这样:

[ThreadStatic]
        static test obj ;
 
        public static test Obj
        {
            get
            {
                if (null == obj)
                {
                    obj = new test();
                    
                }
                return obj;
            }
        }

这样就ok了,但是查了一下msdn,实例只是对于valuetype的类型变量使用ThreadStatic,如果是引用对象的,那么推荐使用LocalDataStoreSlot来保存,小搞了一下,示例如下:

 static LocalDataStoreSlot localSlot;
 
    static ThreadStaticAttr()
    {
        localSlot = Thread.AllocateDataSlot();
    }
 
    public static void ThreadProc()
    {
        while (true)
        {
            if (null == Thread.GetData(localSlot))
                Thread.SetData(localSlot, new test());
 
            ((test)Thread.GetData(localSlot)).i++;
 
            Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, ((test)Thread.GetData(localSlot)).i);
            Thread.Sleep(500);
        }
    }

搞定后,又想了一种方法,其实可以使用Hashtable来自己实现,声明一个Synchronized的Hashtable,然后key使用Thread.CurrentThread.Name不就完了嘛?!实验后,果然奏效,代码如下:

private static Hashtable ht = Hashtable.Synchronized(new Hashtable());
    public static void ThreadProc()
    {
        while (true)
        {
            if (!ht.ContainsKey(Thread.CurrentThread.Name))
                ht.Add(Thread.CurrentThread.Name, new test());
   
         ((test)ht[Thread.CurrentThread.Name]).i++;
 
            Console.WriteLine("{0}:{1}", Thread.CurrentThread.Name, ((test)ht[Thread.CurrentThread.Name]).i);
            Thread.Sleep(500);
        }
    }
这3个示例使用的class非常的简单,如下:
 public class test
   {
       public int i = 0;
   }
而ThreadProc方法及时thread声明时的委托。
原文地址:https://www.cnblogs.com/Seapeak/p/2020178.html