In a multithreaded environment, locking on thread-sensitive resources is important. I often assume collections and such are thread-unsafe, depending on MS documentation, but are simple types thread sensitive too?
Let's take examples. Is it useful to lock int properties access, e.g.
public int SomeProperty
{
get
{
lock (_lock)
{
return _value;
}
}
}
or is a normal getter enough, i.e
public int SomeProperty => _value;
As I understand it, a simple field read is thread safe, but I still see on the web and in some code repositories the first example.
Second question, are values in a single line instruction read sequentially or simultaneously? In other words, do I need to lock when I do that
public TimeSpan GetSomeExampleValue()
{
lock (_lock)
{
return _dateTime1 - _dateTime2;
}
}
or can I simply do
public TimeSpan GetSomeExampleValue()
{
return _dateTime1 - _dateTime2;
}