Forum C# Copying a List gives problems?!

Copying a List gives problems?!

Postby GBurg » January 29th, 2012, 11:15 pm

Hi all,

In my error logs I get this error (it is very rare, twice in thousands of instances):

Destination array was not long enough. Check destIndex and length, and the array's lower bounds.

at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length, Boolean reliable)
at System.Array.Copy(Array sourceArray, Int32 sourceIndex, Array destinationArray, Int32 destinationIndex, Int32 length)
at System.Collections.Generic.List`1.CopyTo(T[] array, Int32 arrayIndex)
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at MyGame.Player.get_bikesCopy()
at MyGame.Room.mhRoundCountdownStart(NetUser nu, Message message)
at MyGame.Room.handleMessage(NetUser nu, Message message)
at MyGame.Room.GotMessage(NetUser nu, Message message)


So it looks like I have an error in get_bikesCopy, right...? This is the code for Player.get_bikesCopy:

Code: Select all
public List<Bike> bikesCopy {
      get {
        List<Bike> bs;
        lock (_bikes) bs = new List<Bike>(_bikes);
        return bs;
      }
    }


There are no cpu aborts... What could be the problem? Seems like bug free code, right? Could it be that this code fails when the _bikes List is not initialized?

Best,

Geert
GBurg
Paid Member
 
Posts: 78
Joined: February 9th, 2011, 10:27 am

Re: Copying a List gives problems?!

Postby GBurg » April 28th, 2012, 9:40 am

Guys, anybody has an idea why this happens?
GBurg
Paid Member
 
Posts: 78
Joined: February 9th, 2011, 10:27 am

Re: Copying a List gives problems?!

Postby FulaFisken » April 29th, 2012, 7:31 pm

you should not lock the list itself, you should have a listLock object that is locked in all places where the list can be changed. Something like below. You might even need to lock while iterating over your list if you want to make sure it isn't changed while doing so.

Code: Select all
private Object listLock = new Object();

public void remove()
{
    lock(listLock)
    {
        //remove from list
    }
}

public void add()
{
    lock(listLock)
    {
        //add to list
    }
}

public void copy()
{
    lock(listLock)
    {
        //copy list
    }
}
Fula Fisken
website blog twitter
Play Game
Astroflux
User avatar
FulaFisken
Paid Member
 
Posts: 139
Joined: March 2nd, 2011, 10:15 am

Re: Copying a List gives problems?!

Postby Benjaminsen » May 1st, 2012, 12:22 pm

What FulaFisken said :)
Benjaminsen
.IO
 
Posts: 1444
Joined: January 12th, 2010, 11:54 am
Location: Denmark


Return to C#



cron