Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Thread.CurrentThread always return same instance?

Can I make Dictionary<Thread, object> to store thread's data and use Thread.CurrentThread to retreive it?

like image 528
Poma Avatar asked Apr 01 '11 13:04

Poma


People also ask

What does thread currentThread () return?

currentThread() method returns a reference to the currently executing thread object.

What is currentThread () method in thread class in Java?

The currentThread() method of thread class is used to return a reference to the currently executing thread object.

What is thread currentThread () getName ()?

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.

Are thread IDs reused?

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.


2 Answers

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.

like image 170
Jon Skeet Avatar answered Nov 15 '22 10:11

Jon Skeet


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.

like image 44
fejesjoco Avatar answered Nov 15 '22 09:11

fejesjoco