VarunPandey
VarunPandey

Reputation: 327

Skipping locked section already in use

I have a critical section which is to be executed only once but is invoked by many scenarios. How can I execute this thread proc and skip all the rest of the calls?

Thanks in advance.

Upvotes: 1

Views: 2342

Answers (5)

Bali C
Bali C

Reputation: 31241

public static bool hasExecuted = false;

static readonly object lockObject = new object();

static void Method()
{
    lock(lockObject)
    {
        if(!hasExecuted)
        {
            // run code
            hasExecuted = true;
        }
    }
}

Upvotes: 1

Kendall Frey
Kendall Frey

Reputation: 44376

// Assuming this uses calls from multiple threads, I used volatile.
volatile bool executed = false;
object lockExcecuted = new object();

void DoSomething()
{
    lock (lockExecuted)
    {
        if (executed) return;
        executed = true;
    }
    // do something
}

Upvotes: 5

YavgenyP
YavgenyP

Reputation: 2123

Depends on ur scenario. If this section returns a value, u can use the new feature of .Net 4.0 - Lazy(T)

Of course, you can always just set a flag within ur critical section, and check its value before executing (which is sometimes being done when using the singleton pattern)

Upvotes: 0

Rob P.
Rob P.

Reputation: 15081

Use lock to allow only one thread to access the critical section and when it's complete set a flag saying it's done.

Upvotes: 0

Peter Ritchie
Peter Ritchie

Reputation: 35870

lock is the preferred method; unless you have more detailed requirements.

EDIT: the addition of "only once" means lock is insufficient.

Upvotes: 0

Related Questions