ThreadLocal的是否有設計問題

1、吐槽

ThreadLocal<T>明顯是.NET從JAVA中來的一個概念,可是這種設計是否出現了問題.工具

很明顯,在JAVA中threadLocal直接是Thread的成員,固然隨着thread這個宿主而存在.spa

但.NET中對於ThreadLocal<T>的設計明顯獨立於Thread以外(固然你能夠說內部有關聯)線程

,起最終結果是ThreadLocal<T>所產生的對象不會隨着線程的終止而釋放.設計

2、問題代碼

/*
 * 由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);
		}
	}
}

4、運行結果內存不釋

 

哪位大俠對此有深刻研究,求賜教.3d

相關文章
相關標籤/搜索