Пример #1
0
        public void GetOrAddWithCallbackOnRemovedReturnsTheOriginalCachedObjectEvenIfNotGettedBeforehand()
        {
            Func <int> fetch = () => 123;
            CacheEntryRemovedArguments removedCallbackArgs = null;
            CacheEntryRemovedCallback  callback            = args => removedCallbackArgs = args;

            sut.GetOrAdd(TestKey, fetch,
                         new CacheItemPolicy
            {
                AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(100),
                RemovedCallback    = callback
            });

            sut.Remove(TestKey); //force removed callback to fire
            while (removedCallbackArgs == null)
            {
                Thread.Sleep(500);
            }

            Assert.AreEqual(123, removedCallbackArgs.CacheItem.Value);
        }
Пример #2
0
        private void CacheItemRemovedCallback(CacheEntryRemovedArguments args)
        {
            if (args.RemovedReason == CacheEntryRemovedReason.Expired)
            {
                logger?.LogInformationAsync($"Expired {args.CacheItem.Key} removed.");
                try
                {
                    string[] parts = args.CacheItem.Key.Split(new[] { ":" }, StringSplitOptions.RemoveEmptyEntries);
                    if (parts.Length == 2)
                    {
                        if (cache.Contains((string)args.CacheItem.Value))
                        {
                            Tuple <ProtocolAdapter, CancellationTokenSource> tuple =
                                (Tuple <ProtocolAdapter, CancellationTokenSource>)cache.Get(
                                    (string)args.CacheItem.Value);
                            if (tuple != null && tuple.Item1 != null)
                            {
                                tuple.Item1.Dispose();
                            }

                            cache.Remove((string)args.CacheItem.Value);
                        }
                    }

                    if (parts.Length == 3)
                    {
                        Tuple <ProtocolAdapter, CancellationTokenSource> tuple =
                            (Tuple <ProtocolAdapter, CancellationTokenSource>)args.CacheItem.Value;
                        if (tuple != null && tuple.Item1 != null)
                        {
                            tuple.Item1.Dispose();
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger?.LogErrorAsync(ex, "Fault UDP cache expiry.").GetAwaiter();
                }
            }
        }
Пример #3
0
        private static void ReCheckCertificate(CacheEntryRemovedArguments arg)
        {
            var key      = int.Parse(arg.CacheItem.Key);
            var oldState = (DateTime)arg.CacheItem.Value;

            using (var db1 = new NotificationCenterContext())
            {
                var cc = db1.ClientCertificates.Single(c => c.ClientId == key);

                db1.Notifications.Add(new Notification()
                {
                    CreatedOn           = DateTime.UtcNow,
                    Message             = $"Certificate {cc.SetialNumber} expired.",
                    NotificationEventId = _notificationEventId,
                    ReferenceRecord     = key,
                    Deleted             = false,
                    Seen = false
                });

                db1.SaveChanges();
            }
        }
Пример #4
0
 /// <summary>
 /// Автовосстановление устаревшего объекта.
 /// Объект восстанавливается на короткое время для использования в других потоках, пока в одном из потоке происходит обновление его значения.
 /// </summary>
 /// <param name="arguments"></param>
 private static void CacheItemRemovedCallBack(CacheEntryRemovedArguments args)
 {
     if (args.CacheItem != null)
     {
         if (args.RemovedReason == CacheEntryRemovedReason.ChangeMonitorChanged ||
             args.RemovedReason == CacheEntryRemovedReason.Expired)
         {
             var value = args.CacheItem.Value;
             if (value != null)
             {
                 var key = args.CacheItem.Key;
                 args.Source.Set(new CacheItem(CalculateDeprecatedKey(key))
                 {
                     Value = value
                 },
                                 new CacheItemPolicy {
                     AbsoluteExpiration = DateTime.Now.AddSeconds(DeprecatedCachePeriod)
                 });
             }
         }
     }
 }
Пример #5
0
        /// <summary>
        /// MemoryCache içinden bir kullanıcı silindiği zaman otomatik olarak CachaManager tarafından çağırılır.
        /// Veritabanı içinden gerekli token bilgilerini siler. Gerek SlidingExpire gerek AbsoluteExpire durumlarında çağırılabilir.
        /// </summary>
        /// <param name="arguments"></param>
        private static void CacheEntryRemovedCallback(CacheEntryRemovedArguments arguments)
        {
            var item = arguments.CacheItem;

            var token     = item.Key;
            var userToken = (UserToken)item.Value;

            var users = App.MeetAppUsers;

            var filter = Builders <BsonDocument> .Filter.Eq("usr", userToken.User.Identity.Name);

            var user = users.Find(filter).FirstAsync();

            if (user.Result == null)
            {
                return;
            }

            var tokens = user.Result["apps"][userToken.FromApp]["tokens"].AsBsonArray;

            for (int i = tokens.Count - 1; i >= 0; i--)
            {
                var doc = tokens[i].AsBsonDocument;

                if (doc["token"].AsString == token)
                {
                    tokens.RemoveAt(i);

                    // Update database
                    var f = Builders <BsonDocument> .Filter.Eq("usr", userToken.User.Identity.Name);

                    users.ReplaceOneAsync(f, user.Result);

                    // işimiz bitti.
                    return;
                }
            }
        }
Пример #6
0
        void ConnectionRemoved(CacheEntryRemovedArguments arguments)
        {
            try
            {
                var lazy = arguments.CacheItem.Value as Lazy <object>;
                if (lazy != null)
                {
                    if (lazy.Value is Runspace)
                    {
                        logger.InfoFormat("Closing runspace: {0}", (lazy.Value as Runspace).ConnectionInfo.ComputerName);
                    }

                    var disposable = lazy.Value as IDisposable;
                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Пример #7
0
        private static void ProcessFiles(CacheEntryRemovedArguments args)
        {
            WriteLine($"* Cache item removed: {args.CacheItem.Key} because {args.RemovedReason}");

            if (args.RemovedReason == CacheEntryRemovedReason.Expired)
            {
                var fileProcessor = new FileProcessor(args.CacheItem.Key);
                fileProcessor.Process();
            }
            else
            {
                WriteLine($"WARNING: {args.CacheItem.Key} was removed unexpectedly and may not be avaiable.");
            }

            /*foreach (var fileName in FilesToProcess.Keys) // May not be in order of adding
             * {
             *  if (FilesToProcess.TryRemove(fileName, out _))
             *  {
             *      var fileProcessor = new FileProcessor(fileName);
             *      fileProcessor.Process();
             *  }
             * }
             */
        }
Пример #8
0
        /// <summary>
        /// For revocable items , move over all revoke ids in cache index and remove them.
        /// </summary>
        private void ItemRemovedCallback(CacheEntryRemovedArguments arguments)
        {
            var cachedItem = ((AsyncCacheItem)arguments.CacheItem.Value).CurrentValueTask;

            if (cachedItem.Status == TaskStatus.RanToCompletion && (cachedItem.Result as IRevocable)?.RevokeKeys != null)
            {
                foreach (var revocationKey in ((IRevocable)cachedItem.Result).RevokeKeys)
                {
                    if (RevokeKeyToCacheKeysIndex.TryGetValue(revocationKey, out HashSet <string> cacheKeys))
                    {
                        lock (cacheKeys)
                        {
                            cacheKeys.Remove(arguments.CacheItem.Key);
                            if (!cacheKeys.Any())
                            {
                                RevokeKeyToCacheKeysIndex.TryRemove(revocationKey, out _);
                            }
                        }
                    }
                }
            }

            Items.Meter(arguments.RemovedReason.ToString(), Unit.Items).Mark();
        }
Пример #9
0
 private void RootCacheItemRemoved(CacheEntryRemovedArguments arguments)
 {
     _rootCacheKeyStored = false;
 }
Пример #10
0
 private static void CachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
 {
     //after deleting event
 }
 private static void CacheEntryRemoved(CacheEntryRemovedArguments arguments)
 {
 }
 public void OnRemovedCallback(CacheEntryRemovedArguments args)
 {
     CacheRemovedCallback(args.CacheItem.Key, args.CacheItem.RegionName, args.RemovedReason.ToString());
 }
Пример #13
0
 private void InstanceTokenRemoved(CacheEntryRemovedArguments arguments)
 {
     this.instanceKey = Guid.NewGuid().ToString();
 }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CacheItemRemovedEvent"/> class.
 /// </summary>
 /// <param name="arguments">
 /// The arguments.
 /// </param>
 public CacheItemRemovedEvent(CacheEntryRemovedArguments arguments)
 {
     this.Key    = arguments.CacheItem.Key;
     this.Value  = arguments.CacheItem.Value;
     this.Reason = arguments.RemovedReason;
 }
Пример #15
0
 private void CacheItemRemovedCallback(CacheEntryRemovedArguments arguments)
 {
     arguments.CacheItem.Value.ToString();
 }
Пример #16
0
 private void RootCacheItemRemovedCallback(CacheEntryRemovedArguments arguments)
 {
     _isRootItemCached = false;
 }
Пример #17
0
 private static void ItemRemovedCallback(CacheEntryRemovedArguments arguments)
 {
     Logger.Debug("Item {0} removed from cache.", arguments.CacheItem.Key);
 }
Пример #18
0
 private static void RemovedKey(CacheEntryRemovedArguments args)
 {
     // Traitement spécifique à la suppression d'un Account
 }
Пример #19
0
 private void DoNothing(CacheEntryRemovedArguments args)
 {
 }
Пример #20
0
 protected virtual void RemovedCallback(CacheEntryRemovedArguments arguments)
 {
 }
Пример #21
0
 private void ItemRemoved(CacheEntryRemovedArguments arguments)
 {
     //refresh the settings cache when expired
 }
 private void Callback(CacheEntryRemovedArguments arguments)
 {
     NotifyDependencyChanged(arguments.Source, EventArgs.Empty);
 }
Пример #23
0
 private void CacheEntryRemove(CacheEntryRemovedArguments arguments)
 {
     _log.Info("Tenant {0} payment cache is expired.", Convert.ToInt32(arguments.CacheItem.Key));
 }
Пример #24
0
 /// <summary>
 /// Responds to cache items being removed from the underlying <see cref="MemoryCache"/>.
 /// </summary>
 /// <param name="e">Provides information about a cache entry that was removed from the cache.</param>
 private static void OnCacheItemRemoved(CacheEntryRemovedArguments e)
 {
     Log.Trace("Saga {0} was removed: {1}.", e.CacheItem.Key, e.RemovedReason);
 }
Пример #25
0
 /// <summary>
 /// 移除后处理函数
 /// </summary>
 /// <param name="arguments"></param>
 private void CacheEntryRemovedCallback(CacheEntryRemovedArguments arguments)
 {
 }
Пример #26
0
 private void RemovedCallback(CacheEntryRemovedArguments arguments)
 {
     Log.Info("RemovedCallback('{0}')", arguments.CacheItem.Key);
 }
Пример #27
0
 private static void AppResourceRemovedCallback(CacheEntryRemovedArguments args)
 {
     // item was removed from cache
 }
Пример #28
0
 private static void MyCachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
 {
     var strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), "| Key‐Name:",
                                arguments.CacheItem.Key, " | Value‐Object:", arguments.CacheItem.Value.ToString());
 }
Пример #29
0
 private void MyCachedItemRemovedCallback(CacheEntryRemovedArguments arguments)
 {
     // Log these values from arguments list
     String strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), " | Key-Name: ", arguments.CacheItem.Key, " | Value-Object: ", arguments.CacheItem.Value.ToString());
 }
Пример #30
0
        private void DispatchQueueExpiry(CacheEntryRemovedArguments e)
        {
            ConcurrentBag <ComplianceMessage> concurrentBag = e.CacheItem.Value as ConcurrentBag <ComplianceMessage>;

            DataflowBlock.SendAsync <IEnumerable <ComplianceMessage> >(this.dispatchBlock, concurrentBag);
        }