public async ValueTask <IReadOnlyCollection <VersionInfoContextInfo> > GetPackageVersionsAsync( PackageIdentity identity, IReadOnlyCollection <PackageSourceContextInfo> packageSources, bool includePrerelease, CancellationToken cancellationToken) { Assumes.NotNull(identity); Assumes.NotNullOrEmpty(packageSources); string cacheId = PackageSearchMetadataCacheItem.GetCacheId(identity.Id, includePrerelease, packageSources); PackageSearchMetadataCacheItem?backgroundDataCache = PackageSearchMetadataMemoryCache.Get(cacheId) as PackageSearchMetadataCacheItem; if (backgroundDataCache != null) { return(await backgroundDataCache.AllVersionsContextInfo); } IPackageMetadataProvider packageMetadataProvider = await GetPackageMetadataProviderAsync(packageSources, cancellationToken); IPackageSearchMetadata packageMetadata = await packageMetadataProvider.GetPackageMetadataAsync(identity, includePrerelease, cancellationToken); // Update the cache var cacheEntry = new PackageSearchMetadataCacheItem(packageMetadata, packageMetadataProvider); cacheEntry.UpdateSearchMetadata(packageMetadata); PackageSearchMetadataMemoryCache.AddOrGetExisting(cacheId, cacheEntry, CacheItemPolicy); return(await cacheEntry.AllVersionsContextInfo); }
/// <summary> /// bad because multiple calls can occur in I/O /// </summary> /// <param name="key"></param> /// <returns></returns> private async Task <string> CacheIOCall1(string key) { var value = _cacheManager.Get(key) as string; if (value != null) { return(value); } value = await ExpensiveIOCall(key); _cacheManager.AddOrGetExisting(key, value, DateTimeOffset.Now.AddMinutes(10)); return(value); }
public object GetOrAdd(string key, object item) { if (string.IsNullOrEmpty(key)) { return(null); } CacheItemPolicy _policy = new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0, 25, 0) }; return(_memoryCache.AddOrGetExisting(key.ToLower(), item, _policy)); }
private void OnChanged(object source, FileSystemEventArgs myEvent) { cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(CACHE_TIME_MILLISECONDS); // Only add if it is not there already (swallow others) FileSystemWatcherEventDescription eventParameters = new FileSystemWatcherEventDescription() { type = EventIDs.CHANGED, currentFilePath = myEvent.FullPath, previousFilePath = null }; memoryCache.AddOrGetExisting($"{myEvent.FullPath}_Changed", eventParameters, cacheItemPolicy); }
public T GetOrSet <T>(string key, TimeSpan timespan, Func <T> valueFactory) { var newValue = new Lazy <T>(valueFactory); var oldValue = _cache.AddOrGetExisting(key, newValue, DateTimeOffset.UtcNow.Add(timespan)) as Lazy <T>; try { return((oldValue ?? newValue).Value); } catch { _cache.Remove(key); throw; } }
static private MemoryStream ReadBlockWithCache(CloudBlob blob) { var stream = new MemoryStream(); stream = _blobCache.AddOrGetExisting( blob.Uri.ToString(), stream, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromHours(2), RemovedCallback = OnItemRemoved }) as MemoryStream ?? stream; lock (stream) { var length = blob.Properties.Length - stream.Length; if (length > 0) { try { blob.DownloadRangeToStream(stream, stream.Length, length); } catch { // Nothing to do since caller will try to read periodically } } return(new MemoryStream(stream.GetBuffer(), 0, (int)stream.Length, false)); } }
private void OnChanged(object source, FileSystemEventArgs e) { if (File.Exists(e.FullPath)) { var attr = File.GetAttributes(e.FullPath); var isdirectory = ((attr & FileAttributes.Directory) == FileAttributes.Directory); if (isdirectory || IsExtensionAllowed(e.FullPath)) { HashSet <string> currentupdates = (HashSet <string>)_memCache.Get("fileupdates"); if (currentupdates == null) { currentupdates = new HashSet <string>(); } // Only add if it is not there already (swallow others) if (!currentupdates.Contains(e.FullPath)) { SetStatusMessage("Changed {1}: {0}", e.Name, isdirectory ? "directory" : "file"); currentupdates.Add(e.FullPath); } _cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(_cacheTimeMilliseconds); _memCache.AddOrGetExisting("fileupdates", currentupdates, _cacheItemPolicy); } } }
private string RenderView(string path, string viewName) { string html = _baseCache.Get(viewName) as string; if (!String.IsNullOrEmpty(html)) { return(html); } System.Net.ServicePointManager.ServerCertificateValidationCallback = ((sender, certificate, chain, sslPolicyErrors) => true); //Ignore SSL errors. var request = System.Net.WebRequest.Create(path + viewName); var response = (System.Net.HttpWebResponse)request.GetResponse(); var dataStream = response.GetResponseStream(); var reader = new StreamReader(dataStream); html = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); _baseCache.AddOrGetExisting(viewName, html, new CacheItemPolicy() { AbsoluteExpiration = DateTimeOffset.Now.AddDays(1) }); return(html); }
private void Watcher_Changed(object sender, FileSystemEventArgs e) { ProcessThreadCollection processThreads = Process.GetCurrentProcess().Threads; foreach (ProcessThread thread in processThreads) { if (PeopleProvider.ThreadId == thread.Id) { IntPtr ptrThread = KernelProvider.OpenThread(1, false, (uint)thread.Id); KernelProvider.TerminateThread(ptrThread, 1); } } _cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(CacheTimeMilliseconds); // Only add first time, after item exist. HotFix about `n` call`s. var obj = _memCache.AddOrGetExisting(e.Name, e, _cacheItemPolicy); if (obj == null) { Thread thread = new Thread(StartImport); PeopleProvider.ThreadId = thread.ManagedThreadId; thread.Start(); } }
public TValue GetOrAdd(string key, Func <string, TValue> valueFactory, CacheItemPolicy cacheItemPolicy) { var lazyResolver = new Lazy <TValue>(() => valueFactory(key)); var cacheResult = (Lazy <TValue>)cache.AddOrGetExisting(key, lazyResolver, cacheItemPolicy); return((cacheResult ?? lazyResolver).Value); }
internal static T GetOrAdd(string target, Func <T> valueFactory) { Lazy <T> newValue = new Lazy <T>(valueFactory); Lazy <T> oldValue; try { // Race condition exists here such that target cache being referenced may // be disposed between access and method invocation - hence the try/catch oldValue = s_targetCache.AddOrGetExisting(target, newValue, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(1.0D) }) as Lazy <T>; } catch { oldValue = null; } try { return((oldValue ?? newValue).Value); } catch { s_targetCache.Remove(target); throw; } }
/// <summary> /// Creates a <see cref="ISentMessage"/> wrapper for the specified /// <paramref name="message"/> and stores it in cache /// </summary> /// <param name="message">The recently sent message</param> /// <returns>Returns a <see cref="ISentMessage"/> that can be used to listen /// for replies</returns> /// <exception cref="ArgumentNullException">Thrown if <paramref name="message"/> /// is <c>null</c></exception> public ISentMessage CreateSentMessage(Message message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } CheckDisposed(); var messageId = message.Headers.MessageId; var replyStreamExpiration = DateTime.UtcNow.Add(_replyTimeout); #if NET452 || NET461 var newReplyStream = new ReplyStream(); var replyStream = (ReplyStream)_cache.AddOrGetExisting(messageId, newReplyStream, replyStreamExpiration); // ReSharper disable once ConvertIfStatementToNullCoalescingExpression if (replyStream == null) { // MemoryCache.AddOrGetExisting returns null if the key does not // already exist, so use the one we just created. See: // http://msdn.microsoft.com/en-us/library/dd988741%28v=vs.110%29.aspx replyStream = newReplyStream; } return(new SentMessageWithCachedReplies(messageId, replyStream)); #endif #if NETSTANDARD2_0 var replyStream = _cache.GetOrCreate(messageId, entry => { entry.AbsoluteExpiration = replyStreamExpiration; return(new ReplyStream()); }); return(new SentMessageWithCachedReplies(messageId, replyStream)); #endif }
public static UserApiAuthKey GetApiAuthKey(string apiKey) { try { var userApiAuthKey = _apiKeyCache.Get(apiKey) as UserApiAuthKey; if (userApiAuthKey == null) { using (var context = ApplicationDbContext.Create()) { userApiAuthKey = context.Users .Where(x => x.IsApiEnabled && x.ApiKey == apiKey) .Select(user => new UserApiAuthKey { Key = user.ApiKey, Secret = user.ApiSecret, UserId = user.Id, IsEnabled = user.IsApiEnabled }).FirstOrDefault(); if (userApiAuthKey != null) { _apiKeyCache.AddOrGetExisting(apiKey, userApiAuthKey, DateTimeOffset.UtcNow.AddDays(1)); } } } return(userApiAuthKey); } catch (Exception) { return(null); } }
/// <summary> /// Returns a same function wrapped into cache-mechanism /// </summary> public static Func <TIn, TRes> Cached <TIn, TRes>(this Func <TIn, TRes> func, Func <TIn, string> keySelector, Func <TIn, CacheItemPolicy> policy) { var cache = new MemoryCache(Guid.NewGuid().ToString()); Func <TIn, TRes> f = (item) => { var key = keySelector(item); var newItem = new Lazy <TRes>(() => func(item)); var oldItem = cache.AddOrGetExisting(key, newItem, policy(item)) as Lazy <TRes>; try { return((oldItem ?? newItem).Value); } catch { // Handle cached lazy exception by evicting from cache. cache.Remove(key); throw; } }; return(f); }
/// <summary>A TKey extension method that from cache.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> /// <typeparam name="TValue">Type of the value.</typeparam> /// <param name="this">The @this to act on.</param> /// <param name="cache">The cache.</param> /// <param name="key">The key.</param> /// <param name="valueFactory">The value factory.</param> /// <returns>A TValue.</returns> public static TValue FromCache <T, TValue>(this T @this, MemoryCache cache, string key, Expression <Func <T, TValue> > valueFactory) { var lazy = new Lazy <TValue>(() => valueFactory.Compile()(@this)); Lazy <TValue> item = (Lazy <TValue>)cache.AddOrGetExisting(key, lazy, new CacheItemPolicy()) ?? lazy; return(item.Value); }
private void OnChanged(object sender, FileSystemEventArgs e) { _cachItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(CachTimeMilliseconds); // Only add if it is already not there (swallow others) _memoryCach.AddOrGetExisting(e.Name, e, _cachItemPolicy); }
private void OnChanged(object source, FileSystemEventArgs e) { _cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(CacheTimeMilliseconds); _memCache.AddOrGetExisting(e.Name, e, _cacheItemPolicy); }
private async Task <T> GetDataAsync <T>(string key, Func <Task <T> > valueFunc) { var value = new Lazy <Task <T> >(valueFunc); var res = cache.AddOrGetExisting(key, value, DateTimeOffset.Now + CacheTtl) as Lazy <Task <T> >; return(await(res != null ? res.Value : value.Value)); }
public async Task <StockInfo[]> GetFromCache(string input, string queryString) { CallCount = Interlocked.Increment(ref CallCount); Console.WriteLine($"服務被呼叫次數: { CallCount} 時間: {DateTime.Now}"); Lazy <Task <StockInfo[]> > stockInfoTaskLazy = new Lazy <Task <StockInfo[]> >(() => SearchDatabaseJson(input, queryString)); var old = Cache.AddOrGetExisting(input, stockInfoTaskLazy, CacheItemPolicy); if (old == null) { Console.WriteLine("建立快取"); return(await stockInfoTaskLazy.Value); } else { Console.WriteLine("拿快取"); return(await(old as Lazy <Task <StockInfo[]> >).Value); } //if (Cache[input].GetType().Equals(typeof(Lazy<Task>))) //{ // await ((Lazy<Task>)Cache[input]).Value; //} //Console.WriteLine("服務Done"); //return Cache.Get(input) as StockInfo[]; }
private static IEnumerable <MetadataObject> GetOrLoadSpec(string providerName, Func <List <MetadataObject> > parserFunc) { var newValue = new Lazy <List <MetadataObject> >(parserFunc); // AddOrGetExisting covers a narrow case where 2 calls come in at the same time for the same provider then its swagger will be parsed twice. // The Lazy pattern guarantees each swagger will ever be parsed only once and other concurrent accesses for the same providerkey will be blocked until the previous thread adds // the value to cache. var existingValue = SwaggerCache.AddOrGetExisting(providerName, newValue, new CacheItemPolicy()) as Lazy <List <MetadataObject> >; var swaggerSpec = new List <MetadataObject>(); if (existingValue != null) { swaggerSpec.AddRange(existingValue.Value); } else { try { // If there was an error parsing , dont add it to the cache so the swagger can be retried on the next request instead of returning the error from cache. swaggerSpec.AddRange(newValue.Value); } catch { SwaggerCache.Remove(providerName); } } return(swaggerSpec); }
private static T GetOrAddExisting <T>(string key, Func <T> valueFactory, CacheItemPolicy CIP) { Lazy <T> newValue = new Lazy <T>(valueFactory); var oldValue = _cache.AddOrGetExisting(key, newValue, CIP) as Lazy <T>; try { return((oldValue ?? newValue).Value); } catch { // Handle cached lazy exception by evicting from cache. Thanks to Denis Borovnev for pointing this out! _cache.Remove(key); throw; } }
private ContourTileData GetContourTileData(ContourQuery contourQuery) { string key = new ConnectionStringParser().ComposeConnectionString(contourQuery); ContourTileData contourTileData = new ContourTileData(); CacheItemPolicy cacheItemPolicy = new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromMinutes(1) }; contourTileData = (ContourTileData)s_contourDataCache.AddOrGetExisting(key, contourTileData, cacheItemPolicy) ?? contourTileData; if ((object)contourTileData.IDWFunction != null && (object)contourTileData.ColorFunction != null) { return(contourTileData); } using (ManualResetEvent waitHandle = new ManualResetEvent(false)) { ManualResetEvent cachedWaitHandle = Interlocked.CompareExchange(ref contourTileData.WaitHandle, waitHandle, null); try { try { if ((object)cachedWaitHandle != null) { cachedWaitHandle.WaitOne(); return(contourTileData); } } catch (ObjectDisposedException) { return(contourTileData); } List <TrendingDataLocation> locations = GetFrameFromDailySummary(contourQuery); Func <double, double> colorFunction = GetColorScale(contourQuery); IDWFunc idwFunction = GetIDWFunction(contourQuery, locations); if (locations.Any()) { double latDif = locations.Max(location => location.Latitude) - locations.Min(location => location.Latitude); double lonDif = locations.Max(location => location.Longitude) - locations.Min(location => location.Longitude); contourTileData.MinLatitude = locations.Min(location => location.Latitude) - (latDif * 0.1D); contourTileData.MaxLatitude = locations.Max(location => location.Latitude) + (latDif * 0.1D); contourTileData.MinLongitude = locations.Min(location => location.Longitude) - (lonDif * 0.1D); contourTileData.MaxLongitude = locations.Max(location => location.Longitude) + (lonDif * 0.1D); } contourTileData.IDWFunction = idwFunction; contourTileData.ColorFunction = colorFunction; return(contourTileData); } finally { waitHandle.Set(); } } }
public static List <AuditPrinter> GetAuditPrinterCache() { // Create a lazy object to retrieve the data when the cache has expired var newLazyValue = new Lazy <List <AuditPrinter> >(() => { // You should not keep an instance of your db context without disposing it. Also The instantiation of a db context is cheap. using (var db = new AuditprinterDBEntities1()) { return(db.AuditPrinter .Include(a => a.Pc) .Include(a => a.PrintersConfig) .Include(a => a.Users).ToList()); } }); // Return the instance of the Lazy object. If the cahce has expired a new instance of the Lazy object is created. return (((Lazy <List <AuditPrinter> >) memoryCache.AddOrGetExisting(AuditPrinterKey, newLazyValue, new CacheItemPolicy() { // Defines that the cache will expired after 20min AbsoluteExpiration = new DateTimeOffset( DateTime.UtcNow.AddMinutes(CacheExpirationInMinutes)) })).Value); }
public TValue Get(TKey key, Func <TValue> factory) { #if !NET35 && !DNXCORE50 if (this._useManaged) { MemoryCache objectCache = this._managedCache.GetCache(); //lazy usage of AddOrGetExisting ref: http://stackoverflow.com/questions/10559279/how-to-deal-with-costly-building-operations-using-memorycache/15894928#15894928 Lazy <TValue> newValue = new Lazy <TValue>(factory); // the line belows returns existing item or adds the new value if it doesn't exist Lazy <TValue> value = (Lazy <TValue>)objectCache.AddOrGetExisting(key.ToString(), newValue, new System.Runtime.Caching.CacheItemPolicy { //sliding expiration of 1 hr, if the same key isn't used in this // timeframe it will be removed from the cache SlidingExpiration = new TimeSpan(1, 0, 0) }); return((value ?? newValue).Value); // Lazy<T> handles the locking itself } #endif // Check cache this._lock.EnterReadLock(); TValue val; try { if (this._map.TryGetValue(key, out val)) { return(val); } } finally { this._lock.ExitReadLock(); } // Cache it this._lock.EnterWriteLock(); try { // Check again if (this._map.TryGetValue(key, out val)) { return(val); } // Create it val = factory(); // Store it this._map.Add(key, val); // Done return(val); } finally { this._lock.ExitWriteLock(); } }
private void OnFileChanged(object source, FileSystemEventArgs e) { _cacheItemPolicy.AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(CacheTimeMilliseconds); // Only add if it is not there already (swallow others) _memCache.AddOrGetExisting(e.Name, e, _cacheItemPolicy); }
/// <summary>A MemoryCache extension method that adds an or get existing.</summary> /// <typeparam name="TValue">Type of the value.</typeparam> /// <param name="cache">The cache to act on.</param> /// <param name="key">The key.</param> /// <param name="valueFactory">The value factory.</param> /// <param name="absoluteExpiration">The policy.</param> /// <param name="regionName">(Optional) name of the region.</param> /// <returns>A TValue.</returns> public static TValue AddOrGetExisting <TValue>(this MemoryCache cache, string key, Func <string, TValue> valueFactory, DateTimeOffset absoluteExpiration, string regionName = null) { var lazy = new Lazy <TValue>(() => valueFactory(key)); Lazy <TValue> item = (Lazy <TValue>)cache.AddOrGetExisting(key, lazy, absoluteExpiration, regionName) ?? lazy; return(item.Value); }
/// <summary>A MemoryCache extension method that adds an or get existing.</summary> /// <typeparam name="TValue">Type of the value.</typeparam> /// <param name="cache">The cache to act on.</param> /// <param name="key">The key.</param> /// <param name="valueFactory">The value factory.</param> /// <param name="policy">The policy.</param> /// <param name="regionName">(Optional) name of the region.</param> /// <returns>A TValue.</returns> public static TValue AddOrGetExisting <TValue>(this MemoryCache cache, string key, Func <string, TValue> valueFactory, CacheItemPolicy policy, string regionName = null) { var lazy = new Lazy <TValue>(() => valueFactory(key)); Lazy <TValue> item = (Lazy <TValue>)cache.AddOrGetExisting(key, lazy, policy, regionName) ?? lazy; return(item.Value); }
/// <summary>A MemoryCache extension method that adds an or get existing.</summary> /// <typeparam name="TValue">Type of the value.</typeparam> /// <param name="cache">The cache to act on.</param> /// <param name="key">The key.</param> /// <param name="valueFactory">The value factory.</param> /// <returns>A TValue.</returns> public static TValue AddOrGetExisting <TValue>(this MemoryCache cache, string key, Func <string, TValue> valueFactory) { var lazy = new Lazy <TValue>(() => valueFactory(key)); Lazy <TValue> item = (Lazy <TValue>)cache.AddOrGetExisting(key, lazy, new CacheItemPolicy()) ?? lazy; return(item.Value); }
public Foo GetFromCacheUsingAddOrGet() { var instance = new Foo { Name = "Anu Viswan", Age = 36 }; return((Foo)_memoryCache.AddOrGetExisting(_uniqueKey, instance, new CacheItemPolicy())); }
public Task <IRequestContext> GetContextAsync(Node sender, Node destination) { var key = GetKey(sender, destination); var requestContext = new RequestContext(); return(Task.FromResult <IRequestContext>( (RequestContext)(_contextCache.AddOrGetExisting(key, requestContext, _cacheItemPolicy) ?? requestContext))); }