Reputation: 1387
I want to lock few lines of code based on a flag
from App config. So based on that flag
I run the application asynchronously or not. So i need to lock execution of few lines of code by checking the flag
. So i need to write code repetitive. Below is the sample
if (flag) {
lock(dataLock){
//few lines of code
}
} else {
//repeat the above code gain here (few lines of code)
}
Is there any alternative way where I can save my repeated codes.
Upvotes: 0
Views: 414
Reputation: 117057
The Monitor.Enter
aproach is best, but you could also do this:
Action fewLinesOfCode = () =>
{
//few lines of code
};
if (flag)
{
lock (dataLock)
{
fewLinesOfCode();
}
}
else
{
fewLinesOfCode();
}
Upvotes: 1
Reputation: 3235
if (flag)
Monitor.Enter(dataLock);
// few lines of code
if (Monitor.IsEntered(dataLock))
Monitor.Exit(dataLock);
Upvotes: 2
Reputation: 23
You could call a function with your outsourced code from within the lock and even from within the else statement. That would at least reduce your overhead and repetitive code.
if(flag==true){
lock(dataLock){
fewLines();
}
}else{
fewLines();
}
[...]
public void fewLines(){
// put your few lines here.
}
that would run the function from the locked context.
Upvotes: 1
Reputation: 153
Use Monitor.Enter instead of Lock() {} ? Enter and exit with the if statement.
Upvotes: 1