【发布时间】:2012-03-28 17:23:35
【问题描述】:
我正在寻找一种方法来解释在调用 ReferenceEquals() 时添加高级业务逻辑是不合理的。
这是我遇到问题的代码 sn-p(方法中的前提条件,旨在在我们在错误的线程上时抛出):
if (!object.ReferenceEquals(Thread.CurrentThread, RequestHandlerThread))
这样写可靠吗:
if (Thread.CurrentThread != RequestHandlerThread)
根据我在教程中经常看到的内容,我建议在比较中使用 ManagedThreadIds。 Adversary 说引用相等的比较似乎更面向对象。
这是(大致)我在 Reflector 的 System.Object 与 .NET 4.0 视图中看到的内容。请记住,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 ==" 实现之外的任何地方使用。
-
ReferenceEquals() 用于
Equals()实现
标签: c# .net multithreading coding-style