How do I detect multi-threaded use?

c#, multithreading

Solution

No it is not sufficient !

A managed thread id can be reused by the CLR, so `if(threadId!=Thread.CurrentThread.ManagedThreadId)` can return `false` even is the calling thread is different from the one used to construct the object.

What you are trying to achieve is possible through references comparisons:

if (!object.ReferenceEquals(Thread.CurrentThread, ThreadThatCreatedThis))
// ...

EDIT :

MSDN says however that :

The value of the ManagedThreadId property does not vary over time, even if unmanaged code that hosts the common language runtime implements the thread as a fiber.

http://msdn.microsoft.com/en-us/library/system.threading.thread.managedthreadid%28v=vs.110%29.aspx

Problem

Is it sufficient to compare the `ManagedThreadId` at the time an object is created and at the time a method is called to verify that it isn't being used in a multithreading scenario? ``` public class SingleThreadSafe { private readonly int threadId; public SingleThreadSafe() { threadId = Thread.CurrentThread.ManagedThreadId; } public void DoSomethingUsefulButNotThreadSafe() { if(threadId!=Thread.CurrentThread.ManagedThreadId) { throw new InvalidOperationException( "This object is being accessed by a thread different than the one that created it. " + " But no effort has been made to make this object thread safe."); } //Do something useful, like use a previously established DbConnection } } ``` My intuition is often wrong about threading, so I wanted to check to see if there are edge cases I should be keeping in mind.

Original source

Related problems