Poma
Poma

Reputation: 8484

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?

Upvotes: 5

Views: 233

Answers (2)

fejesjoco
fejesjoco

Reputation: 11903

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.

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1502386

You can, but you'd also need to synchronize (as Dictionary<,> isn't thread-safe).

Alternatives:

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.

Upvotes: 10

Related Questions