积极答复者
多线程下 获取 Object.GetHashCode() 值是否相等?

问题
-
测试单件模式的代码
public class Singleton { private static Singleton instance; // 私有的默认的构造函数,防止 默认的构造函数 被外部调用; private Singleton() { } /// <summary> /// 获取一个 Singleton 模式的实例. /// </summary> public static Singleton Instance { get { if (instance == null) { instance = new Singleton(); } return Singleton.instance; } } }
下面是测试代码
static private IList log = new List<Int32>(); [TestMethod()] public void InstanceTestByThread() { int threadCount = 2; // 创建一定数量的线程执行体 Thread[] threads = new Thread[threadCount]; for (int i = 0; i < threadCount; i++) { ThreadStart work = new ThreadStart( delegate { Log.Add(Design_Pattern.Singleton.Single_Thread.Without_Parameters.Singleton.Instance.GetHashCode()); } ); threads[i] = new Thread(work); } // 执行线程 foreach (Thread item in threads) { Thread.Sleep(1000); item.Start(); } for (int i = 0; i < threadCount - 1; i++) { for (int j = i + 1; j < threadCount; j++) { Assert.IsNotNull(SingletonTest.Log[i]); Assert.IsNotNull(SingletonTest.Log[j]); Assert.AreNotEqual(SingletonTest.Log[i], SingletonTest.Log[j]); } } }
答案
-
看 MSDN
http://msdn.microsoft.com/zh-cn/library/system.object.gethashcode(VS.80).aspx
给实现者的说明:
如果两个类型相同的对象表示相同的值,则哈希函数必须为两个对象返回相同的常数值。
你在单粒模式下,不要说两个对象,根本是同一个对象,哈希值当然相同。
学习学习....- 已建议为答案 Min ZhuModerator 2011年5月31日 9:10
- 已标记为答案 钱仔 2011年6月2日 17:53
-
你好,
哈希值本身与线程是没有关系的。同一实例在同样的状态下在不同的线程中获取的哈希值是相同的。
你看到的单线程应该指的是线程安全的问题。如果Singleton的实例是线程不安全的,那么你在多线程中使用这些实例的时候就需要考虑线程同步,
Min Zhu [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 钱仔 2011年6月2日 17:53
全部回复
-
看 MSDN
http://msdn.microsoft.com/zh-cn/library/system.object.gethashcode(VS.80).aspx
给实现者的说明:
如果两个类型相同的对象表示相同的值,则哈希函数必须为两个对象返回相同的常数值。
你在单粒模式下,不要说两个对象,根本是同一个对象,哈希值当然相同。
学习学习....- 已建议为答案 Min ZhuModerator 2011年5月31日 9:10
- 已标记为答案 钱仔 2011年6月2日 17:53
-
什么问题?
Eric Yang [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
你好,
哈希值本身与线程是没有关系的。同一实例在同样的状态下在不同的线程中获取的哈希值是相同的。
你看到的单线程应该指的是线程安全的问题。如果Singleton的实例是线程不安全的,那么你在多线程中使用这些实例的时候就需要考虑线程同步,
Min Zhu [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 钱仔 2011年6月2日 17:53