> Local variables are always thread-safe, since they are not shared among
> threads. This is because each thread has its own stack (where the local
> variables are stored).
That's certainly true. However, if the local variable is a reference to
an object which is also being used and potentially changed on another
thread, you need to use locks, volatile variables or explicit memory
barriers to ensure safety.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Cool Guy - 11 Sep 2005 18:15 GMT
> That's certainly true. However, if the local variable is a reference to
> an object which is also being used and potentially changed on another
> thread, you need to use locks, volatile variables or explicit memory
> barriers to ensure safety.
In this case it's never being changed, although it is being used on another
thread.
Will the locking I'm already doing suffice here?
Jon Skeet [C# MVP] - 11 Sep 2005 19:12 GMT
> > That's certainly true. However, if the local variable is a reference to
> > an object which is also being used and potentially changed on another
[quoted text clipped - 5 lines]
>
> Will the locking I'm already doing suffice here?
Yes, that's fine. By the time you release the lock in thread A, all the
writes are guaranteed to be visible to other threads, and by the time
you've acquired the lock in thread B, thread B is guaranteed to only
use values which are "correct" as of the time of the lock acquisition.

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Hmmmm - be careful, in C# 2.0 anonymous delegates change the landscape a bit. Variables that appear to be local turn out to be allocated on the heap.
void DoIt()
{
int x = 0;
MyDel d = delegate
{
for( int i = 0; i < 2000; i++ )
{
x += i;
}
};
IAsyncResult ar = d.BeginInvoke(null, null);
x++;
d.EndInvoke(ar);
}
In x is now being updated from 2 threads and is (under the covers) being allocated on the head in a temporary object.
Regards
Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
Local variables are always thread-safe, since they are not shared among
threads. This is because each thread has its own stack (where the local
variables are stored).