Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 551
Pieter Avatar asked Oct 20 '25 03:10

Pieter


1 Answers

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.

like image 122
Marc Gravell Avatar answered Oct 22 '25 18:10

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!