What is the advantage of ThreadStatic, ThreadLocal, GetData over instantiating an object for a thread?

A friend asked me what would be better than ThreadStatic or ThreadLocal. Checking the document I told him that ThreadLocal looks more convenient, accessible with .NET 4.0, but I don’t understand why use any of them to instantiate the object for the thread. Their goal is to preserve "local-data streams", so you can call methods less clumsily and avoid blocking in some cases. When I need such local data, I always created something like:

    class ThreadHandler
    {
        SomeClass A;

        public ThreadHandler (SomeClass A)
        {
            this.A = A;
        }

        public void Worker ()
        {
        }
    }

, ( ThreadHandler ( SomeClass()). TheWorkerMethod).Start(), , , ThreadHandler , Thread ThreadHandler, ThreadHandler , , threadpool QueueUserWorkItem Thread(). , , , .

google, ThreadLocal , , ThreadLocal , ThreadStatic, , , , , . , .

, - , ThreadStatic/ThreadLocal , . - ThreadLocal ?

UPD: , , "java" Google, . , - ThreadLocal .

+4
4

ThreadLocal .

, , - " " .

, , , . , , 10 , 3 , . , .

, , , .

- , ( , - ), . , : - , Thread?

, , , .

+2

ThreadLocal<T> Dictionary<Thread, T>. , , , - , . ThreadLocal , , , , GC.

, , Dictionary<Thread, T>. .

+2

ThreadLocal has 2 advantages compared to the attribute of the ThreadStatic attribute, you can avoid the definition of a class field and create a built-in function for lazy loading. your approach to manual collection requires locking, if you look at the source code of ThreadLocal, you will see that it is optimized for this particular case.

0
source

ThreadLocal can get benfits when an object of type T is new and gc often. And it is safe.

0
source

Source: https://habr.com/ru/post/1547714/


All Articles