c# – 如何检测多线程使用?

前端之家收集整理的这篇文章主要介绍了c# – 如何检测多线程使用?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在创建对象时和在调用方法以验证它不在多线程场景中使用时,是否足以比较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

原文链接:https://www.f2er.com/csharp/94708.html

猜你在找的C#相关文章