简体   繁体   中英

Throw exception if calling thread is not the thread that created the object

I want to create an instance of my custom class. For example, I have two threads T1 and T2 . If I create instance from T1 , any access to that instance from T2 should throw an exception. Like in WinForms, when I try access control from thread which is not UI thread.

How to achieve this? Should I store reference to current thread or should I keep some unique ID of the current thread? (if that ID exists). Which mechanism shoud I use?

Basically it will be a singleton that generates random numbers form given seed. I want to block access to this singleton from other threads, because I need to run my app again with same seed to reproduce my scenario. If I will alow to use this class from other threads, then reproduction will be not possible because threads start/stops/do actions in unpredictible order.

I think you could use Thread.CurrentThread.ManagedThreadId for that purpose.

Note, however, that these IDs might get re-used at some time, so they may not be unique accross the lifespan of your application. However, given the scenario you've described, I think that this should not be an issue.

Also you need to be aware that your 'guard' may not play well with async coding depending on how and where it is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM