Earlz Earlz - 3 years ago 74
C# Question

How to execute a piece of code exactly once with multithreading in mind?

I have a function which does "migration" from an old format to a new format. I need this to occur in the constructor of my object, but not the static constructor because an argument is needed. How can I have a piece of code only execute exactly one time?

For some context:

class Foo
{
public Foo(string bar)
{
ShouldOnlyExecuteOnce(bar);
}
}


and then usage could be (with each line a different thread)

var f = new Foo("bar");
var fb = new Foo("meh");
etc


How can I properly guard the "
ShouldOnlyExecuteOnce
" method?

Because this is a sort of "migration" type function, I want for the first object created to "win" and get to migrate the old data into this new object. Later objects that get constructed should not attempt to execute this function, even if their arguments are different

Answer Source

You could use double check locking.

class Foo
{
    private static bool ShouldOnlyExecuteOnceExecuted = false;
    private static readonly object Locker = new object();

    public Foo(string bar)
    {
        SetShouldOnlyExecuteOnce(bar);
    }

    private void SetShouldOnlyExecuteOnce(string bar)
    {
        if(!ShouldOnlyExecuteOnceExecuted)
        {
            lock(Locker)
            {
                if(!ShouldOnlyExecuteOnceExecuted)
                {
                    ShouldOnlyExecuteOnce(bar);
                    ShouldOnlyExecuteOnceExecuted = true;
                }
            }
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download