Forum C# Delegates and Synchronization

Delegates and Synchronization

Postby FulaFisken » September 2nd, 2011, 10:07 am

Hi there.

I have a question regarding delegates and synchronization. We have an issue with that in our object pooling.

If we have several delegate calls running simultaneously altering a list will be a hazardous. eg.

Code: Select all
public void CreateDrop(string key, Callback<Drop> successCallback)
{
  g.dataManager.GetData(Table.DROPS(), key, delegate(DatabaseObject obj)
  {
      Drop drop =  GetInactiveDrop()
      .. set props ...
      successCallback(drop);
  }
}

public Drop GetInactiveDrop()
{
      Drop drop = inactiveDrops[0];
      inactiveDrops.removeAt(0);
      return drop;
}


In the example above multiple drops might get a reference to the same inactiveDrop since GetInactiveDrop can be called asynchronously.

Now, I talked with a friend that has a bit of experience with threading in Java and he told me about synchronized methods http://download.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html. Which forces the function to be synchronized almost like a transaction.

After a bit of google I found this in C#:
Code: Select all
[MethodImpl(MethodImplOptions.Synchronized)]


Code: Select all
public void CreateDrop(string key, Callback<Drop> successCallback)
{
  g.dataManager.GetData(Table.DROPS(), key, delegate(DatabaseObject obj)
  {
      Drop drop =  GetInactiveDrop()
      .. set props ...
      successCallback(drop);
  }
}

[MethodImpl(MethodImplOptions.Synchronized)]
public Drop GetInactiveDrop()
{
      Drop drop = inactiveDrops[0];
      inactiveDrops.removeAt(0);
      return drop;
}


Is this the correct way to handle these kind of issues?

Does it have any implications on PlayerIO and server performance?

Is there any different than using lock(this)? eg.

Code: Select all
public Drop GetInactiveDrop()
{
      lock(this)
      {
          Drop drop = inactiveDrops[0];
          inactiveDrops.removeAt(0);
          return drop;
      }
}


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

Re: Delegates and Synchronization

Postby Henrik » September 2nd, 2011, 6:02 pm

1) Use lock.
2) Lock on the actual object that you want to access synchronously.
3) Lock for as short a time as possible.

So in your example, I would write it like this:

Code: Select all
public Drop GetInactiveDrop() {
    lock(inactiveDrops) {
        Drop drop = inactiveDrops[0];
        inactiveDrops.removeAt(0);
        return drop;
    }
}
Henrik
.IO
 
Posts: 1880
Joined: January 4th, 2010, 1:53 pm

Re: Delegates and Synchronization

Postby FulaFisken » September 2nd, 2011, 7:14 pm

Thanks!
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#