比较线程是否相等

Gre*_*egC 2 .net c# multithreading coding-style

我正在寻找一种方法来解释通过调用ReferenceEquals()来使用高级业务逻辑是不合理的.

这是一个我遇到问题的代码片段(方法中的前置条件,如果我们在一个错误的线程上,则设计为抛出):

if (!object.ReferenceEquals(Thread.CurrentThread, RequestHandlerThread))
Run Code Online (Sandbox Code Playgroud)

写这个是可靠的:

if (Thread.CurrentThread != RequestHandlerThread)
Run Code Online (Sandbox Code Playgroud)

我建议在比较中使用ManagedThreadIds基于我在教程中常见的内容.对手说参考平等的比较看起来更像面向对象.

这是(大致)我在Reflector的.NET 4.0 System.Object视图中看到的.请记住,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)));
}
Run Code Online (Sandbox Code Playgroud)

以下是一些基本测试,验证线程池上的操作......我是否错过了任何重要的测试?

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("");
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

小智 7

试着不要讲道,但是......一般来说,如果有一个身份属性可以使用,在这种情况下

Thread.ManagedThreadId
Run Code Online (Sandbox Code Playgroud)

它应该用于相等比较,除非执行代码存在性能约束.指针比较的语义与等式有很大不同.此外,指针比较取决于mscorlib中Thread的实现.