在创建对象时和在调用方法以验证它不在多线程场景中使用时,是否足以比较ManagedThreadId?
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 } }
我的直觉往往是错误的线程,所以我想检查,看看是否有边缘案件我应该牢记.
解决方法
不,还不够!
托管线程ID可以由CLR重用,因此如果(threadId!= Thread.CurrentThread.ManagedThreadId)可以返回false,即使调用线程与构造对象的线程不同.
您通过参考比较可以实现您想要实现的目标:
if (!object.ReferenceEquals(Thread.CurrentThread,ThreadThatCreatedThis)) // ...
编辑:
MSDN然而说:
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