views:

26

answers:

1

In using .NET asynchronous delegates for the first time, I was surprised to empirically discover that when changing an instance member value (e.g. an int) in the asynch method (running in the new thread), the value of the instance member running in the original thread was also changed.

I thought that when a new thread is created, instance member values are copied from the original thread, but then isolated from the original.

Could someone help me to better understand what's going on under the covers? In my research, most books/articles speak of static variables, but not instance variables. Thanks!

+1  A: 

Asynchronous delegates don't do any copying, nor do they make your fields thread-local. All they do is queue up the delegate to run in a thread from the thread pool. Whatever that delegate does affects whatever it was going to affect all along. This could easily mean that the changes it makes are not thread-safe.

Steven Sudit
There may be confusion on user394007's part about the difference between the instance of the object containing the delegate, and the instance of Thread which is executing... TLS is unique per Thread, and managed as part of the Thread, not innately part of the delegate.
Tetsujin no Oni
(Changed user394007 to Dave :)) So it sounds like the the thread running the asynch delegate and the main thread are both referencing the same object instance - thus the caution about thread-safety - correct?
Dave
Correct. Normally, you'd want each thread to lock a shared resource during the time period that they need to use it.
Steven Sudit