How can I use memcached in C# to store and retrieve data upto 1gb?

152 views Asked by At

I am saving a datatable and then trying to fetch data from memcache. I tried increasing the max_bytes using the command

memcached.exe -d start -m 1024

I am saving data using this code:

public void SaveDataTableInMemoryCache(string key, DataTable dataTable)
    {
        var config = new MemcachedClientConfiguration();
        config.AddServer("localhost", 11211);
        using (var memcachedClient = new MemcachedClient(config))
        {
            byte[] searchSavedData = memcachedClient.Get<byte[]>(key);

            if (searchSavedData != null)
            {
                memcachedClient.Remove(key);
            }
            // Set an expiration time of 24 hours (1 day)
            TimeSpan expirationTime = TimeSpan.FromHours(24);

            // Serialize the DataTable into a byte array before storing it in Memcached
            byte[] serializedData = SerializeDataTable(dataTable);

            // Store the serialized DataTable in Memcached with a 24-hour expiration time
            memcachedClient.Store(StoreMode.Set, key, serializedData, expirationTime);
        }
    }

private byte[] SerializeDataTable(DataTable dataTable)
        {
            DataSet dataSet = new DataSet();
            dataSet.Tables.Add(dataTable);

            using (var ms = new System.IO.MemoryStream())
            {
                dataSet.WriteXml(ms, XmlWriteMode.WriteSchema); // Include schema
                return ms.ToArray();
            }
        }


public DataTable RetrieveDataTableFromCache(string key)
        {
            var config = new MemcachedClientConfiguration();
            config.AddServer("localhost", 11211);
            using (var memcachedClient = new MemcachedClient(config))
            {
                // Retrieve the serialized DataTable from Memcached
                byte[] serializedData = memcachedClient.Get<byte[]>(key);

                if (serializedData != null)
                {
                    // Deserialize the byte array back into a DataTable
                    return DeserializeDataTable(serializedData);
                }
            } // DataTable not found in cache
            return null;
        }

And trying to fetch data from memcache. It is working for a datatable which has less than 200 rows with 15 columns.

How can I take this up to 1gb datatable?

0

There are 0 answers