我正在尋找一種方法來解釋通過調用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