Add /Update Cache Data with Streams
The GetCacheStream method is used for adding and updating the data within a stream. If the key provided with GetCacheStream
API does not exist in the cache, the data written on the stream is added to the cache.
If an item already exists in the cache with the provided key, binary data written on the stream is appended with the existing data against the specified key.
Pre-Requisites
- Install the following NuGet packages in your application:
- Include the following namespaces in your application:
Alachisoft.NCache.Runtime.Caching
Alachisoft.NCache.Client
Alachisoft.NCache.Runtime.Exceptions
- Cache must be running.
- Make sure that the data being added is serializable.
- For API details, refer to: ICache, CacheStream, StreamMode, CacheStreamAttributes.
- To ensure the operation is fail safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
try
{
// Pre-condition: Cache is already connected
// Generate a unique cache key
string key = "StreamKey";
// Initialize CacheStream object
CacheStream cacheStream = null;
// Set StreamMode object to Read mode
StreamMode streamMode = StreamMode.Write;
// Provide the streamMode object to CacheStreamAttributes object
var streamAttributes = new CacheStreamAttributes(streamMode);
// ReadAllBytes returns the stream from the provided path in a byte Array
byte[] dataToWrite = System.IO.File.ReadAllBytes("C:\\ncache-manual.pdf");
// Use GetCacheStream to set streamAttributes against the specified key
cacheStream = cache.GetCacheStream(key, streamAttributes);
// Write data in buffer
cacheStream.Write(dataToWrite, 0, dataToWrite.Length);
// Close stream
}
catch (OperationFailedException ex)
{
// Exception can occur due to:
// Connection Failures
// Operation Timeout
// Operation performed during state transfer
}
catch (Exception ex)
{
// handle exception
// This includes StreamException
}
Additional Resources
NCache provides sample application for streaming on GitHub.
See Also
Continuous Query
Read/Write Streams
Retrieving Data from Streams
Closing a Stream
Security and Encryption