//////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2007-2020 , Inc. All Rights Reserved. // //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; namespace GCSeries.Core.Sdk { public abstract class ZNativeResourceCache where T : ZNativeResource { //////////////////////////////////////////////////////////////////////// // Public Methods //////////////////////////////////////////////////////////////////////// /// /// Clears the internal cache of resources. /// public void ClearCache() { this._cache.Clear(); } //////////////////////////////////////////////////////////////////////// // Protected Methods //////////////////////////////////////////////////////////////////////// /// /// Adds a resource to the cache. /// /// /// /// The resource to be added to the cache. /// protected void AddToCache(ZNativeResource resource) { this._cache.Add(resource.NativePtr, resource); } /// /// Removes a resource from the cache based on its specified /// native pointer. /// /// /// /// The native pointer corresponding to the resource to be removed. /// protected void RemoveFromCache(IntPtr nativePtr) { this._cache.Remove(nativePtr); } /// /// Remove a resource from the cache. /// /// /// /// A reference to the resource to be removed. /// protected void RemoveFromCache(ZNativeResource resource) { this._cache.Remove(resource.NativePtr); } /// /// Gets a resource from the cache based on a specified native /// pointer. /// /// /// /// The native pointer corresponding to the resource to retrieve. /// /// /// /// A reference to a resource based on its corresponding native /// pointer. /// protected T GetCachedResource(IntPtr nativePtr) { if (nativePtr == IntPtr.Zero) { return null; } ZNativeResource resource = null; if (!this._cache.TryGetValue(nativePtr, out resource)) { return null; } return (resource as T); } /// /// Get a resource from the cache if it exists. Otherwise, create /// and return a new resource and add it to the cache. /// /// /// /// The native pointer corresponding to the resource to create. /// /// /// Callback function used to create the resource if it doesn't /// already exist in the cache. /// /// /// /// The existing or newly created resource. /// protected T GetOrCreateCachedResource( IntPtr nativePtr, Func createFunc) { if (nativePtr == IntPtr.Zero) { return null; } T resource = this.GetCachedResource(nativePtr); if (resource == null) { resource = createFunc(nativePtr); this.AddToCache(resource); } return resource; } //////////////////////////////////////////////////////////////////////// // Private Members //////////////////////////////////////////////////////////////////////// private Dictionary _cache = new Dictionary(); } }