.NET asynchronous delegates and object instance members
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 开发者_如何学JAVAvariables, but not instance variables. Thanks!
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.
精彩评论