Skip to main content
RSS feed Subscribe to feed


Data Cache

The data cache is general purpose. It supports many data types. Multiple instances may be created.


The DataCache provides methods similar to dictionaries. Since the cache owner handles the keys, multiple cache instances can be created to simplify the creation of unique keys. If cached data is shared across threads, it is recommended to wrap the cache in a service.

If an object is present in the cache, retrieving it will be fast. Still, anything in a cache can be erased at any time, returning false when calling TryGetValue, and the object must be recreated. Image objects like bitmaps and metafiles cannot the stored directly in the cache, but can be stored as BinaryLargeObject. Note that the cache can store simple data types, which is useful when simple data types result from complex operations.


The following example shows how to create a data cache and use it for images:

string[] fileNames = new string[] {@"C:\Temp\Scatter Plot.jpg", @"C:\Temp\Bar Chart.jpg"};
BinaryLargeObject blob = null;

// Create a cache with image file paths as keys.
using (DataCache<string, BinaryLargeObject> cache = new DataCache<string, BinaryLargeObject>())
    for (int i = 0; i < fileNames.Length; i++)
        // First try to retrieve the image from the cache
        if (!cache.TryGetValue(fileNames[i], out blob))
            // No image found. Create it from file instead.
            FileStream stream = new FileStream(fileNames[i], FileMode.Open);

            // Read the data to a BinaryLargeObject
            blob = BinaryLargeObject.Create(stream);

            // Close the stream

            // Store the blob in the cache
            cache.Set(fileNames[i], blob);

        // Create the image from the blob
        Image img = Image.FromStream(blob.GetByteStream());

        // Do something with the image
        // ...

        // Dispose the image