c# - Member collection iteration thread safety -
i have background thread performing operation similar this:
class="lang-cs prettyprint-override">class client { public readonlycollection<ipaddress> servers { get; private set; } void updateservers( list<ipaddress> servers ) { // called on background thread this.servers = new readonlycollection( servers ); } } and on main thread, consumer may want iterate servers property.
i know foreach, iteration thread-safe because iterator belong old instance if updateservers called during iteration.
with for loop, iteration can made safe with:
var serverlist = client.servers; ( int x = 0 ; x < serverlist.count ; ++x ) { dosomething( serverlist[ x ] ); // ... } but i'm wondering if there way guarantee compiler generate (or forcefulness generate, if doesn't already) code above, if consumer decides iterate with:
class="lang-cs prettyprint-override">for ( int x = 0 ; x < client.servers.count ; ++x )
the compiler generates code tell to. there might optimizations avoid loading value of field on , over, shouldn't rely on those.
so, possible compiler generate code way, doesn't have to, should write code if didn't.
also, things can tricky (for example, think should create field volatile). best selection utilize locks, unless cause real performance problem (which happens rarely).
c# multithreading design thread-safety
No comments:
Post a Comment