Discussion thread

I am curious if the following sample code is thread safe:

public class Test
{
    [ThreadStatic]
    private static Foo current;

    public static Foo GetFoo()
    {
        return current ?? (current = new Foo());
    }
}

public class Foo
{
}

Normally I would use Lazy<T>, but since there is a separate variable in one thread, the property should be essentially thread safe, is this correct?

Thanks.

+4
source share
2 answers

The code you provide looks great thread-wise. If you are comfortable with Lazy<T>, you can use ThreadLocal<T>one that works in a similar way, but stores its value in streaming mode and in a stream.

// Thread-Local variable that yields a name for a thread
ThreadLocal<string> ThreadName = new ThreadLocal<string>(() =>
{
    return "Thread" + Thread.CurrentThread.ManagedThreadId;
});

https://msdn.microsoft.com/en-us/library/dd642243(v=vs.110).aspx

+4
source

Thread -safe, , Thread , , , Singleton, ThreadStaticAttribute.

, , Thread - Thread -safe-like Random .

Random.Next 0 Threads, ThreadStatic Thread.

, ThreadStatic Thread.

ThreadLocal<T>, , , Lazy<T> Thread.

, ThreadLocal<T> Value.

, GetFoo, ThreadStatic.

+1

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


All Articles