nunu
nunu

Reputation: 3252

C# Multi-thread: Set value once and use it with all rest of the threads

As I am working on multi-threaded application (.Net Windows service) with .Net, I need to make sure the following things.

So, basically, I want to update the value (of C# static field) for the first time only (When my windows service start), and want my all other thread should use the latest value set by first thread.

So, I want to update the value ONLY ONCE, then rest other thread should use only that value.

Would anybody please tell me that How would I achieve this?

Thanks in advance!

Upvotes: 1

Views: 1078

Answers (4)

Tadas Šukys
Tadas Šukys

Reputation: 4220

As I4V suggested - use Lazy<T> and for simplicity I suggest hide it under a read-only property:

static readonly Lazy<T> t = new Lazy<T>(() => new T());
static public T Value { get { return t.Value; }}

Upvotes: 0

I4V
I4V

Reputation: 35353

You can use Lazy<T> for this

static Lazy<string> _singleton = new Lazy<string>(() =>
    {
        return new WebClient().DownloadString("http://www.stackoverflow.com");
    }, true);

Second parameter (true) is "isThreadSafe".

Now you can get the value in many threads, many times using _singleton.Value;

Upvotes: 2

Mzf
Mzf

Reputation: 5260

Seem like Threadsafe Singleton will do the job. The below code example use double-check locking

This will ensure you that the creation of the singleton is 1 time and thread safe

public sealed class Singleton
{

   private static volatile Singleton singleton = null;
   private static readonly object singletonLock = new object();

   private Singleton() {//place your code here}

   public static Singleton GetInstance()
   {
       if (singleton == null)
       {
           lock (singletonLock)
           {
               if (singleton == null)
              {
                  singleton = new Singleton();
              }
           }
        }

        return singleton;
   }
}

Edit: Add volatile due to members comment.

Upvotes: 0

Martin Mulder
Martin Mulder

Reputation: 12944

Why not use this type of singleton. The static constructor is called ONLY once. And since static initializations are part of the static constructor, the initialization is also called only once. The keyword volatile is not required, since the _instance field can not have any other value after construction.

public sealed class Singleton
{
    private static Singleton _instance= new Singleton();

    private Singleton() 
    {
    }

    public static Singleton Instance
    {
        get
        {
            return _instance;
        }
    }
}

Upvotes: 0

Related Questions