Reputation: 1327
In a piece of code I'm currently refactoring there is a dictionary with saved threads.
Now, inside a lock
block i'm comparing the current thread with the ones saved in the dictionary with
if (dictionary.ContainsKey(id) && dictionary[id] != null &&
Thread.CurrentThread.Equals(dictionary[id].OwnerThread))
{
release(...);
}
Now I would like to replace the Equals()
with
Thread.CurrentThread.ManagedThreadId == dictionary[id].OwnerThread.ManagedThreadId
More specifically, can ever Thread.Equals return false while a ManagedThreadId comparison would be true (for the same thread) ?
Upvotes: 0
Views: 442
Reputation: 21729
The two ways of checking for equality are not comparable.
Equals
for a Thread
is going to be a reference equals, because Thread
is a class that doesn't override this behavior. The managed thread ID is just a comparison of integers.
I wouldn't worry about performance. I'd say you're right to use the managed thread ID for comparison as that is more correct. Note, though, that it is possible for you to later get a thread that was created with the same ID as a previous thread (assuming that previous thread no longer exists).
Upvotes: 2