Put Compare Exchange Operation



Syntax

Method:

public PutCompareExchangeValueOperation(string key, T value, long index)
Parameter Type Description
key string Object identifier under which value is saved, unique in the database scope across the cluster. This string can be up to 512 bytes.
value T The value to be saved for the specified key.
index long * 0 if creating a new key
* The current version of Value when updating a value for an existing key.

Returned object:

public class CompareExchangeResult<T>
{
    public bool Successful;
    public T Value;
    public long Index;
}
Return Value Type Description
Successful bool * True if the save operation has completed successfully
* False if the save operation failed
Value T * The value that was saved if operation was successful
* The currently existing value in the server upon failure
Index long * The version number of the value that was saved upon success
* The currently existing version number in the server upon failure

Note:

When calling the 'Put' operation, the index from the request is compared to the index that is currently stored in the server (compare stage).
The value is updated only if the two are equal (exchange stage).

Example I - Create a new key

CompareExchangeResult<string> compareExchangeResult
    = store.Operations.Send(
        new PutCompareExchangeValueOperation<string>("Emails/foo@example.org", "users/123", 0));

bool successful = compareExchangeResult.Successful;
// If successfull is true: then Key 'foo@example.org' now has the value of "users/123"

Example II - Update an existing key

// Get existing value
CompareExchangeValue<User> readResult =
    store.Operations.Send(
        new GetCompareExchangeValueOperation<User>("AdminUser"));

readResult.Value.Age++;

// Update value
CompareExchangeResult<User> saveResult
    = store.Operations.Send(
        new PutCompareExchangeValueOperation<User>("AdminUser", readResult.Value, readResult.Index));

// The save result is successful only if 'index' wasn't changed between the read and write operations
bool saveResultSuccessful = saveResult.Successful;