views:

171

answers:

1

Part of a C# application I'm writing requires collecting data from a service provider's database for each account associated to a user. When the user logs into the app a call is made to start updating the accounts from the service provider's database. Since lots operations are performed on the third party's end the process of getting their information could take a while so I don't want to wait for each account just to start the process of updating. My question is, is there any issues (maybe threading issues) with calling a asynchronous method inside of a loop?

+3  A: 

The only loop-specific issue is that if you use anonymous methods that refer to loop variables, each time around the loop an instance of the anonymous method object will be created but they will all refer to the same loop variable, so they will see it change its value as the loop executes. So make a copy of the loop variable inside the loop.

foreach (var thing in collection)
{
    var copy = thing;

    Action a = () =>
               {
                   // refer to copy, not thing
               }
}
Daniel Earwicker