Pieter
Pieter

Reputation: 32755

Checking whether the current thread equals the thread on which an object was constructed

Is there a way to check within someObj.someMethod() if it is being executed on the same thread on which someObj was created? This could save me a debugging headache later on if I mess up certain concurrency constraints.

Upvotes: 3

Views: 698

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1062660

The only way to do that is to store the thread-id when you create it. On .NET 4.5:

readonly int ownerThreadId;
public SomeType() {
    ownerThreadId = Environment.CurrentManagedThreadId;
}

then check against that same term in someMethod.

Note that on other framework versions, you might need:

ownerThreadId = Thread.CurrentThread.ManagedThreadId;

instead.

Upvotes: 3

Related Questions