Append Operation in Memcached using C# (Detailed Guide w/ Code Examples)

Use Case(s)

The append operation in memcached is primarily used to add or concatenate additional data to an existing key-value pair. This can be useful when you want to update the value of a specific key without having to read its current value (to reduce network overhead).

Code Examples

We'll be using EnyimMemcached, a popular .NET client for memcached, for these examples.

  1. Setting up and appending values
var config = new MemcachedClientConfiguration(); config.AddServer("localhost", 11211); using (var client = new MemcachedClient(config)) { //Set a key with initial value client.Store(StoreMode.Set, "key1", "value1"); //Append data to the existing key bool appendResult = client.Append("key1", ",appendedValue"); Console.WriteLine($"Append Result: {appendResult}"); //Get the updated value var updatedValue = client.Get<string>("key1"); Console.WriteLine($"Updated Value: {updatedValue}"); }

In this example, we first set an initial value ("value1") for a key ("key1"). We then append a string (",appendedValue") to this key. The final output would be "value1,appendedValue".

  1. Handle append failure
using (var client = new MemcachedClient(config)) { //Append data to non-existing key bool appendResult = client.Append("nonexistingKey", ",appendedValue"); Console.WriteLine($"Append Result: {appendResult}"); }

In this case, append operation will fail because it's attempted on a non-existing key. The append operation does not create a new key.

Best Practices

  • Only use append operations for cases where reading the existing value, updating it on client side and then writing it back to memcached is not efficient.
  • Be aware that memcached does not support appending complex objects or serialized data out of the box. Appending works best with string data.

Common Mistakes

  • Attempting to append to a non-existent key. The append operation doesn't create a new key; it only adds to an existing one.
  • Trying to append complex objects or serialized data. The append operation in Memcached is designed to work primarily with simple string values.


Q: Can I append complex objects or serialized data using memcached?

A: No, you can't directly append complex objects or serialized data as memcached supports append operation primarily for simple string values.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.