Can I make Dictionary<Thread, object>
to store thread's data and use Thread.CurrentThread to retreive it?
currentThread() method returns a reference to the currently executing thread object.
The currentThread() method of thread class is used to return a reference to the currently executing thread object.
Thread. currentThread() returns a reference to the thread that is currently executing. In the above example, I've used thread's getName() method to print the name of the current thread. Every thread has a name. you can create a thread with a custom name using Thread(String name) constructor.
Because thread IDs can be reused without notice as threads are created and destroyed, this value is more reliable than the value returned by the GetCurrentThreadId function.
You can, but you'd also need to synchronize (as Dictionary<,>
isn't thread-safe).
Alternatives:
ThreadStaticAttribute
ThreadLocal<T>
(.NET 4)Of course, one benefit of using a dictionary over ThreadStaticAttibute
is that you don't need to worry about garbage as much, or indeed black magic. If you're using .NET 4 though, ThreadLocal<T>
is possibly your best option.
Yes you could, if you want to access other threads' data, but you should take a look at ThreadStaticAttribute or ThreadLocal first, it's much better if threads only need to see their own data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With