IS there an example of CAS anywhere?

I tried this over on the Unity forums with no luck.

Does anyone have a code example for changing a RoomProperty in Photon using CAS, that includes the error handling?

I have a float[] as a custom property. The various players can change elements of the float array. However, because of concurrency, while I try to change one element, another player may try to change a different element.

Ultimately what I am looking for (psuedocode)

ChangeRoomProperties()
{
ReadRoomProperties() //casting them to an array[]
alter the desired element
recreate Hashtable
room.SetCustomProperties(prop, oldvalueProp);
if error == incorrect oldValueProp
{
ChangeRoomProperties()
}
}

Best Answer

Answers

  • Hi @Spektre,

    Here is how to use CAS for room properties, it's an extension method you can directly use:
    
    using ExitGames.Client.Photon;
    using Photon.Realtime;
    
    public static class RoomExtensions 
    {
        public static bool SetCustomPropertySafe(this Room room, string key, object newValue, WebFlags webFlags = null)
        {
            if (room == null)
            {
                return false;
            }
            if (room.IsOffline)
            {
                return false;
            }
            if (!room.CustomProperties.ContainsKey(key))
            {
                return false;
            }
            Hashtable newProps = new Hashtable(1) {{key, newValue}};
            Hashtable oldProps = new Hashtable(1) {{key, room.CustomProperties[key]}};
            return room.LoadBalancingClient.OpSetCustomPropertiesOfRoom(newProps, oldProps, webFlags);
        }
    }
    Use as follows:

    PhotonNetwork.CurrentRoom.SetCustomPropertySafe(key, newValue);

    You should know that:

    - initializing (i.e. first time creating a new property) using CAS is not supported
    - there is no error callback for when SetProperties fails due to CAS
  • Thanks JohnTube.

    Is a flag set or anything to tell you the attempted CAS write failed?

    Per the docs.

    https://doc.photonengine.com/en-us/pun/current/gameplay/synchronization-and-state

    "SetCustomProperties has an optional expectedValues parameter, which can be used as condition. With expectedValues, the server will only update the properties, if its current key-values match the ones in expectedValues. Updates with outdated expectedValues will be ignored (the clients get an error as a result, others won't notice the failed update).
Sign In or Register to comment.