Reputation: 327
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
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
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
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
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
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