简体   繁体   中英

Anonymous c# delegate within a loop

Hi all i am trying to write and anonymous delegate. as the integer variable is shared among the delegate i need it to be the local instance of every delegate such that rs[0] always gets nics[0], rs[1] always gets nics[1] and so on... how will i achieve this.

for (int i = 0; i < nics.Count; i++)
   {
         rs[i] = new RollingSeries(monitor, new RollingSeries.NextValueDelegate(delegate()
         {
            return GetNetworkUtilization(nics[i]);
          }));
    }

Abdul khaliq

Make a local copy of i :

   for (int i = 0; i < nics.Count; i++)
   {
         int j = i;
         rs[i] = new RollingSeries(monitor, new RollingSeries.NextValueDelegate(delegate()
         {
            return GetNetworkUtilization(nics[j]);
          }));
    }

The Beauty of Closures

Use a local to get a different value per iteration

for (int i = 0; i < nics.Count; i++)
   {
         int localI = i;
         rs[i] = new RollingSeries(monitor, new RollingSeries.NextValueDelegate(delegate()
         {
            return GetNetworkUtilization(nics[localI]);
          }));
    }

Put int j = i inside your loop and refer to j within the lambda expression.

If you are curious about why this happens, here is an MSDN blog entry containing a detailed technical explanation: Closing over the loop variable considered harmful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM