如何检测多线程使用?

Mat*_*tin 10 c# multithreading

是否足以比较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
    }
}
Run Code Online (Sandbox Code Playgroud)

我的直觉在线程方面经常是错误的,所以我想检查一下我是否应该记住边缘情况.

qua*_*dev 4

不,这还不够!

托管线程 ID可以由 CLR重用,因此即使调用线程与用于构造对象的线程不同,if(threadId!=Thread.CurrentThread.ManagedThreadId)可以返回。false

您想要实现的目标可以通过参考比较来实现:

if (!object.ReferenceEquals(Thread.CurrentThread, ThreadThatCreatedThis))
// ...
Run Code Online (Sandbox Code Playgroud)

编辑 :

然而MSDN说:

ManagedThreadId 属性的值不会随时间变化,即使承载公共语言运行时的非托管代码将线程实现为纤程也是如此。

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