加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:46:09 所属栏目:百科 来源:网络整理
导读:在创建对象时和在调用方法以验证它不在多线程场景中使用时,是否足以比较ManagedThreadId? public class SingleThreadSafe{ private readonly int threadId; public SingleThreadSafe() { threadId = Thread.CurrentThread.ManagedThreadId; } public void D
在创建对象时和在调用方法以验证它不在多线程场景中使用时,是否足以比较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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读