Reputation: 9847
I have critical section in my application which contains a lot of code: which is better way to locking access in threadMethod:
A) lock all block:
private object locker = new object();
private void threadMethod()
{
while(true)
{
lock(locker)
{
// do work - a lot of code here
}
Thread.Sleep(2000);
}
}
B) Use additional locked access member canWork
:
private static object locker = new object();
private bool canWork;
private bool CanWork
{
get { lock(locker) { return this.canWork; } }
set { lock(locker) { this.canWork = value; } }
}
private void threadMethod()
{
while(true)
{
if(CanWork)
{
// do work - a lot of code here
}
Thread.Sleep(2000);
}
}
and somewhere in code
CanWork = false;
Upvotes: 3
Views: 1777
Reputation: 11754
est link:
http://msdn.microsoft.com/en-us/magazine/cc188793.aspx#fig7
Best usage is - declare a new private sync object - use "lock(synObject) { code here ... }
Upvotes: 0
Reputation: 205
I would use the Monitor instead. Plus do you really want while(true) because this will repeat forever?
private object syncObject = new object();
private void threadMethod()
{
bool tryToRun = true;
while(tryToRun)
{
if(Monitor.TryEnter(syncObject))
{
tryToRun = false;
// do work - a lot of code here
Monitor.Exit(syncObject);
}
else
{
Thread.Sleep(2000); // Possibly knock this up the how long you expect the lock to be held for.
}
}
}
Upvotes: 1
Reputation: 838216
Neither is particularly good.
Instead try to pass immutable arguments to your method (for example a copy of the data). You will probably still need to lock for constructing the arguments and for collecting the results but this is hopefully a much shorter period of time.
Upvotes: 4
Reputation: 5003
The second approach will likely lead to race conditions. Can your "a lot of code" be separated in several critical/non critical chunks?
Upvotes: 1