Forum C# Lock and List Question.

Lock and List Question.

Postby FulaFisken » September 9th, 2011, 7:21 pm

We have this issue in our code. My question is, can it happen because we have the return statement outside of the lock? Or do we have problem elsewhere? We have locked all code snippets that add or remove from the list with the unitListLock object.

Code: Select all
Collection was modified; enumeration operation may not execute.
First seen 18 hours ago, latest 43 minutes ago. (Delete 2 errors)

   at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at System.Collections.Generic.List`1.Enumerator.MoveNext()


Code: Select all
private Unit FindNearestInRangeTarget()
{
  Unit nearestTarget = null;
  lock (g.unitManager.unitListLock)
  {
      foreach (Unit u in g.unitManager.units)
      {
         SetNearestTarget(u, nearestTarget, out nearestTarget);
      }
   }
   return nearestTarget;
}
Fula Fisken
website blog twitter
Play Game
Astroflux
User avatar
FulaFisken
Paid Member
 
Posts: 139
Joined: March 2nd, 2011, 10:15 am

Re: Lock and List Question.

Postby Mrx3D » September 11th, 2011, 9:57 am

HEy, And you are also locking on the same object, when adding or removing "Unites" from the list?
Mrx3D
Paid Member
 
Posts: 31
Joined: February 4th, 2010, 8:32 pm

Re: Lock and List Question.

Postby FulaFisken » September 12th, 2011, 9:14 am

Yes, we do lock the same object while removing, and adding.

Code: Select all
public void Remove(Unit unit)
{
    lock (unitListLock)
    {
        units.Remove(unit);
    }
}


Code: Select all
[MethodImpl(MethodImplOptions.Synchronized)]
public void Add(Unit unit)
{
    lock (unitListLock)
    {
        id++;
        if (unit.Id != 0)
           g.PlayerIO.ErrorLog.WriteError("ERROR: UnitId already in use. Lock doesn't work.");

        unit.Id = id;
        units.Add(unit);
    }
}


Thank you for the reply!
Fula Fisken
website blog twitter
Play Game
Astroflux
User avatar
FulaFisken
Paid Member
 
Posts: 139
Joined: March 2nd, 2011, 10:15 am

Re: Lock and List Question.

Postby Mrx3D » September 12th, 2011, 8:03 pm

The "[MethodImpl(MethodImplOptions.Synchronized)]" attribute might be messing with your lock's, I'm not sure as i have never used that attribute with lock's
Mrx3D
Paid Member
 
Posts: 31
Joined: February 4th, 2010, 8:32 pm

Re: Lock and List Question.

Postby FulaFisken » September 13th, 2011, 3:59 pm

Mrx3D wrote:The "[MethodImpl(MethodImplOptions.Synchronized)]" attribute might be messing with your lock's, I'm not sure as i have never used that attribute with lock's


If we remove that it gets much worse. I don't know why, but it looks like id++ is iterated within lock(unitListLock) if we don't synch the whole method.
Fula Fisken
website blog twitter
Play Game
Astroflux
User avatar
FulaFisken
Paid Member
 
Posts: 139
Joined: March 2nd, 2011, 10:15 am


Return to C#