How to execute a block of code only once on a multithreading environment? How to execute a block of code only once on a multithreading environment? wpf wpf

How to execute a block of code only once on a multithreading environment?


Use the Lazy<T> Class:

private readonly Lazy<MyObject> myObject;public MyClass(){    myObject = new Lazy<MyObject>(() =>    {        return MyService.LoadMyObject();    }, LazyThreadSafetyMode.ExecutionAndPublication);}public bool IsModelLoaded{    get { return myObject.IsValueCreated; }}public override MyObject Load(){    return myObject.Value;}


Simplest would be to add

[MethodImpl(MethodImplOptions.Synchronized)]public override MyObject Load(){   //snip}

but be aware this puts a lock on the entire object, not just the method. Not really great practice.

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimploptions.aspx

Synchronized

Specifies that the method can be executed by only one thread at a time. Static methods lock on the type, whereas instance methods lock on the instance. Only one thread can execute in any of the instance functions, and only one thread can execute in any of a class's static functions.


I are trying to implement singleton pattern. But your version is not thread safe. Read more here: http://www.dofactory.com/Patterns/PatternSingleton.aspx. Try to use this implementation:

public sealed class Singleton{    static Singleton instance=null;    static readonly object padlock = new object();    Singleton()    {    }    public static Singleton Instance    {        get        {            lock (padlock)            {                if (instance==null)                {                    instance = new Singleton();                }                return instance;            }        }    }}