我正在寻找一种方法来解释通过调用ReferenceEquals()来抛出高级业务逻辑是不合理的。比较线程的相等性
下面是一个代码片段,我有一个问题(在方法,设计前提抛出,如果我们是在一个错误的线程):
if (!object.ReferenceEquals(Thread.CurrentThread, RequestHandlerThread))
它是可靠的,而不是写:
if (Thread.CurrentThread != RequestHandlerThread)
我建议在比较中使用ManagedThreadIds,基于我在教程中常见的内容。对手说,参照平等的比较似乎更加面向对象。
这里(大致)是我在.NET 4.0的System.Object的Reflector视图中看到的。请记住,Thread类是密封的,并且对于operator ==没有重载。
public static bool ReferenceEquals(object objA, object objB)
{
return (objA == objB);
}
public static bool Equals(object objA, object objB)
{
return (objA == objB ||
(objA != null && objB != null && objA.Equals(objB)));
}
这是一些基本的测试,验证线程池上的操作......我错过了任何重要的测试吗?
using System.Threading;
using System.Diagnostics;
using System.Threading.Tasks;
namespace ConsoleApplicationX
{
class Program
{
static readonly Thread mainThread;
static Program()
{
mainThread = Thread.CurrentThread;
}
static void Main(string[] args)
{
Thread thread = Thread.CurrentThread;
if (thread != Thread.CurrentThread)
Debug.Fail("");
if(Thread.CurrentThread != thread)
Debug.Fail("");
if (thread != mainThread)
Debug.Fail("");
var task = Task.Factory.StartNew(() => RunOnBackground(thread));
task.Wait();
var anotherThread = new Thread(new ParameterizedThreadStart(RunInAnotherThread));
anotherThread.Start(thread);
}
static void RunOnBackground(Thread fromInitial)
{
if (Thread.CurrentThread == fromInitial)
Debug.Fail("");
if (fromInitial != mainThread)
Debug.Fail("");
}
static void RunInAnotherThread(object fromInitialAsObject)
{
var fromInitial = (Thread)fromInitialAsObject;
if (Thread.CurrentThread == fromInitial)
Debug.Fail("");
if (fromInitial != mainThread)
Debug.Fail("");
}
}
}
FWIW,我个人从未见过System.Object.ReferenceEquals在“operator ==”的实现之外的任何地方使用。 – 2012-03-28 17:30:22
在Equals()'实现中使用的ReferenceEquals() – sll 2012-03-28 20:17:57