Varun Setia
What is Most Optimized Thread Safe Way To Lock Resources for Singleton Pattern?

Problem Statement is: the lock statement is used in case of implementing the Thread Safe Singleton Pattern.
The question is, we need to lock a resource but using a lock(x){} statement is bit expensive as per the interviewer. What is the most efficient or optimum way to lock a resource without using lock statement?

Is there any catch or trick in this question?

By Varun Setia in C# on Jul 26 2020
  • Aisha Omar
    May, 2023 15

    one way to implement thread safe single is via use of static.

    public sealed class Singleton
    {
    private static readonly Singleton obj = new Singleton();
    public static Singleton Obj { get { return obj; } }

    1. public sealed class Singleton
    2. {
    3. private static readonly Singleton obj = new Singleton();
    4. public static Singleton Obj
    5. {
    6. get
    7. {
    8. return obj;
    9. }
    10. }
    11. private Singleton() {}
    12. }

    To access the instance of Singleton Class:
    Singleton mySingleton = Singleton.Obj;

    • 0


Most Popular Job Functions


MOST LIKED QUESTIONS