Synchronized Get/Set

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi
I am a new pie to Visual Stadio 2005 C# NETCF 2.0

I have a property call

public bool Name
{
get
{
return this.name;
}
set
{
this.name = value;
}
}

Cause there is a couple of thread will access this method, So I want to
synchronized this variable, but I do not how to lock it.
I have found a solution call ReadwriterLock, but it does not support NETCF2.0

How to write this function?

Thanks
 
C# contains a method called lock that prevents further changes to the object
until exited from the lock. Other methods include creating a mutex or
creating a ManualResetEvent. There are many articles on google and msdn that
explain how to perform Thread Synchronization.

Rick D.
Contractor
 
Generally would would only lock reference types but there occations you might
want to lock value types, counters etc. For this,
System.Threading.Interlocked can be used.
int mysharedint = 0;
IE: System.Threading.Interlocked(ref mysharedint);

I have never used this with booleans, I guess you would cast it.
 
jeff je napisal:
Cause there is a couple of thread will access this method, So I want to
synchronized this variable, but I do not how to lock it.
I have found a solution call ReadwriterLock, but it does not support NETCF2.0

locking these two (simple) methods won't solve sychronization issues
(get-set property = two methods),
you have to lock resource for the time it must be consistent.

bad code:

if (x.Name == true) // read
{
// do stuff

// x.Name becomes false from another thread

x.Name = false; // write
}

proper code:

lock(x)
{
if (x.Name == true) // read
{
// do stuff

// other threads waiting for lock to be released

x.Name = false; // write
}
}

all threads accessing this property must synchronize, so there
won't be any inconsistencies.

Maxxel
 
Back
Top