ThreadLocal<T>的是否有设计问题

一、吐槽

ThreadLocal<T>明显是.NET从JAVA中来的一个概念,但是这种设计是否出现了问题.

很明显,在JAVA中threadLocal直接是Thread的成员,当然随着thread这个宿主而存在.

但.NET中对于ThreadLocal<T>的设计明显独立于Thread之外(当然你可以说内部有关联)

,起最终结果是ThreadLocal<T>所产生的对象不会随着线程的终止而释放.

二、问题代码

/*
 * 由SharpDevelop创建。
 * 用户: qsmy
 * 日期: 2016/12/31
 * 时间: 9:31
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Threading;

namespace ThreadLocalTest
{
	public class MyObject
	{
		public static readonly ThreadLocal<MyObject> threadLocal 
			= new ThreadLocal<MyObject>(true);
		
		public static MyObject GetCurrentThreadMyObject(String name)
		{
			if (threadLocal.Value == null) {
				threadLocal.Value = new MyObject(name);
			}
			return threadLocal.Value;
		}
		
		String _name;
		public byte[] _bs;
		public MyObject(String name)
		{
			_name = name;
			Console.WriteLine("创建MyObject.name=" + name);
			_bs=new byte[(1024*1024*500)];
			for (int i = 0; i < _bs.Length; i++) {
				_bs[i]=3;
			}
		}
		~MyObject()
		{
			Console.WriteLine("析构MyObject.name=" + _name);
		}
		public void Dispose()
		{
			 threadLocal.Value = null;
			 threadLocal.Values.Clear();
			//Console.WriteLine(MyObject.threadLocal.Values.Count);
		}
	}
	class Program
	{
		 
		public static void Main(string[] args)
		{
			 
			Thread th1 = new Thread((state) => {			                      	
				var obj = MyObject.GetCurrentThreadMyObject("obj1");
				obj.ToString();
				Console.WriteLine("t1.id=" + Thread.CurrentThread.ManagedThreadId);
				 
				obj.Dispose();
				Thread.CurrentThread.Abort();
			});
			th1.Start();
			
			 
			Thread th2 = new Thread((state) => {
				var obj = MyObject.GetCurrentThreadMyObject("obj2");
				obj.ToString();
				Console.WriteLine("t2.id=" + Thread.CurrentThread.ManagedThreadId);
				obj.Dispose();
				Thread.CurrentThread.Abort();
			});
			th2.Start();
			
			Thread.Sleep(20000);
			Console.WriteLine(th1.ThreadState);
			 
			 
			
			Console.ReadKey(true);
		}
	}
}

四、运行结果内存不释

 

哪位大侠对此有深入研究,求赐教.

 

posted @ 2016-12-31 12:05  月明时勤  阅读(...)  评论(... 编辑 收藏