How to detect cross thread access in .NET (enforce thread affinity)?

后端 未结 3 1957
耶瑟儿~
耶瑟儿~ 2021-02-06 09:20

I\'m writing a special data structure that will be available in a .NET library and one of the features of this data structure is that is will be thread safe provided that only o

3条回答
  •  Happy的楠姐
    2021-02-06 09:39

    Rather than compare thread ID's you should store the ambient Thread in your class during construction.

    class SingleThreadedClass
    {
        private Thread ownerThread;
    
        public SingleThreadedClass()
        {
            this.ownerThread = Thread.CurrentThread;
        }
    
        public void Read(...)
        {
            if (Thread.CurrentThread != this.ownerThread)
                throw new InvalidOperationException();
        }
    
        public void TakeOwnership()
        {
            this.ownerThread = Thread.CurrentThread;
        }
    }
    

提交回复
热议问题