H
Harold Howe
Howdy,
1- Are property reads in effect volatile? Or is the compiler allowed to
optimize property reads away? ie
class foo
{
public int bar
{
get { return m_bar;}
set { m_bar = value;}
}
private int m_bar;
}
....
foo f = new foo();
f.bar=1000;
....// make f available to another thread
while (f.bar==1000)
{
...
}
On each pass through the loop, am I guaranteed that the compiler will
requery the get routine for the bar property? If so, then properties are
logically volatile. If not, then my loop will never end, even if a
background thread sets f.bar to a different value.
2- Are string assignments atomic? Hejlsberg's c# book claims that
assignments to ref types are atomic. Strings are references, but they
often don't feel like it. In searching these groups, I read several
posters that claim that string assignments are not atomic. Hence my doubt.
I am asking this question because I am trying to create a thread safe
object that has a string property. If string assignments are not atomic,
then returning a string value from a property getter is not thread safe,
and I will need a lock.
public String Value
{
get { return m_Value; // atomic??? }
// or
get
{
String result;
lock(this)
{
result = m_Value;
}
return result;
}
}
I would like to avoid the lock when reading if possible.
h^2
keywords: read, write, atomicity, assignment, properties.
1- Are property reads in effect volatile? Or is the compiler allowed to
optimize property reads away? ie
class foo
{
public int bar
{
get { return m_bar;}
set { m_bar = value;}
}
private int m_bar;
}
....
foo f = new foo();
f.bar=1000;
....// make f available to another thread
while (f.bar==1000)
{
...
}
On each pass through the loop, am I guaranteed that the compiler will
requery the get routine for the bar property? If so, then properties are
logically volatile. If not, then my loop will never end, even if a
background thread sets f.bar to a different value.
2- Are string assignments atomic? Hejlsberg's c# book claims that
assignments to ref types are atomic. Strings are references, but they
often don't feel like it. In searching these groups, I read several
posters that claim that string assignments are not atomic. Hence my doubt.
I am asking this question because I am trying to create a thread safe
object that has a string property. If string assignments are not atomic,
then returning a string value from a property getter is not thread safe,
and I will need a lock.
public String Value
{
get { return m_Value; // atomic??? }
// or
get
{
String result;
lock(this)
{
result = m_Value;
}
return result;
}
}
I would like to avoid the lock when reading if possible.
h^2
keywords: read, write, atomicity, assignment, properties.