Ejemplo n.º 1
0
        public void Test1()
        {
            var cache = new LRUCache <string, string>(5);

            cache.Add("item1", "1");
            cache.Add("item2", "2");
            cache.Add("item3", "3");
            Assert.True(cache.Contains("item2"));
            Assert.False(cache.Contains("item4"));
        }
Ejemplo n.º 2
0
 private void StampNegativeCache(UUID assetId)
 {
     lock (_negativeCache)
     {
         if (_negativeCache.Contains(assetId))
         {
             _negativeCache.Remove(assetId);
         }
         _negativeCache.Add(assetId, DateTime.Now);
     }
     // m_log.InfoFormat("[ASSET CACHE]: Add/update {0} to negative cache.", assetId);
 }
Ejemplo n.º 3
0
        public static void DownloadSelfAvatar(GetAvatarResult resultHandler, ErrorHandler errorHandler, bool ignoreCache = false, [CallerMemberName] string caller = null)
        {
            try
            {
                String address = ChatConnection.Instance.WebHost;
                int    port    = ChatConnection.Instance.WebPort;
                String url     = String.Format(GetSelfAvatarURL, address, port);

                if (avatarCache.Contains("Self") && !ignoreCache)
                {
                    resultHandler(avatarCache.Get("Self"));
                }
                else
                {
                    new Task(() =>
                    {
                        using (WebClient client = new WebClient())
                        {
                            Console.WriteLine(caller + " downloading self avatar");
                            client.Headers.Add(ClientSession.HeaderToken, ChatConnection.Instance.Session.SessionID);
                            byte[] data = client.DownloadData(url);

                            BitmapImage bitmap = new BitmapImage();
                            bitmap.BeginInit();
                            bitmap.StreamSource = new MemoryStream(data);
                            bitmap.EndInit();

                            if (resultHandler != null)
                            {
                                bitmap.Freeze();
                                Application.Current.Dispatcher.Invoke(() =>
                                {
                                    avatarCache.AddReplace("Self", bitmap);
                                    resultHandler(bitmap);
                                });
                            }
                        }
                    }).Start();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                if (errorHandler != null)
                {
                    errorHandler(e);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 格式 [bundle/]asset
        /// </summary>
        /// <param name="assetPath"></param>
        /// <returns></returns>
        public static AssetId Parse(string assetPath)
        {
            if (_Cache.Contains(assetPath))
            {
                return(_Cache.Get(assetPath));
            }

            if (string.IsNullOrEmpty(assetPath))
            {
                throw new Exception("素材路径为空");
            }

            var lastDiv = assetPath.LastIndexOf('/');

            if (lastDiv == -1)
            {
                throw new Exception($"未指定bundle {assetPath}");
            }

            var result = new AssetId(
                assetPath.Substring(0, lastDiv),
                assetPath.Substring(lastDiv + 1));

            _Cache.Add(assetPath, result);
            return(result);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Start the server to receive datagrams.  Before calling this method, set the 'DatagramReceived' event.
        /// </summary>
        public void StartServer()
        {
            State state = new State(_MaxDatagramSize);

            _Socket.BeginReceiveFrom(state.Buffer, 0, _MaxDatagramSize, SocketFlags.None, ref _Endpoint, _ReceiveCallback = (ar) =>
            {
                State so = (State)ar.AsyncState;
                _Socket.BeginReceiveFrom(so.Buffer, 0, _MaxDatagramSize, SocketFlags.None, ref _Endpoint, _ReceiveCallback, so);
                int bytes = _Socket.EndReceiveFrom(ar, ref _Endpoint);

                string ipPort = _Endpoint.ToString();
                string ip     = null;
                int port      = 0;
                Common.ParseIpPort(ipPort, out ip, out port);

                if (!_RemoteSockets.Contains(ipPort))
                {
                    _RemoteSockets.AddReplace(ipPort, _Socket);
                    EndpointDetected?.Invoke(this, new EndpointMetadata(ip, port));
                }

                if (bytes == so.Buffer.Length)
                {
                    DatagramReceived?.Invoke(this, new Datagram(ip, port, so.Buffer));
                }
                else
                {
                    byte[] buffer = new byte[bytes];
                    Buffer.BlockCopy(so.Buffer, 0, buffer, 0, bytes);
                    DatagramReceived?.Invoke(this, new Datagram(ip, port, buffer));
                }
            }, state);
        }
Ejemplo n.º 6
0
        public void ShowImage(String imageURL)
        {
            try
            {
                LoadingAhihi.Visibility = Visibility.Visible;
                VideoFull.Close();

                VideoFull.Visibility = Visibility.Hidden;
                ImgFull.Visibility   = Visibility.Hidden;

                if (ImgCache.Contains(imageURL))
                {
                    ImgFull.Source = ImgCache.Get(imageURL);

                    ImgFull.MaxHeight = ImgFull.Source.Height;
                    ImgFull.MaxWidth  = ImgFull.Source.Width;

                    ImgFull.Visibility      = Visibility.Visible;
                    LoadingAhihi.Visibility = Visibility.Hidden;
                }
                else
                {
                    if (imgThread != null && imgThread.IsAlive)
                    {
                        imgThread.Abort();
                    }
                    imgThread = new Thread(() =>
                    {
                        try
                        {
                            WebClient wc       = new WebClient();
                            BitmapFrame bitmap = BitmapFrame.Create(new MemoryStream(wc.DownloadData(imageURL)));
                            wc.Dispose();
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                ImgCache.AddReplace(imageURL, bitmap);
                                ImgFull.Source = bitmap;

                                ImgFull.MaxHeight  = bitmap.PixelHeight;
                                ImgFull.MaxWidth   = bitmap.PixelWidth;
                                ImgFull.Visibility = Visibility.Visible;

                                LoadingAhihi.Visibility = Visibility.Hidden;
                            });
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                    });
                    imgThread.IsBackground = true;
                    imgThread.Start();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 7
0
        public void TestSimpleCacheAndRetrieval()
        {
            var    cache    = new LRUCache <UUID, string>(MAX_CACHE_SIZE);
            string testData = "Test Data";
            UUID   id       = UUID.Random();

            cache.Add(id, testData);
            Assert.IsTrue(cache.Contains(id));
            Assert.AreEqual(1, cache.Size, "Size property was wrong");

            Assert.IsTrue(cache.TryGetValue(id, out string entry));
            Assert.AreEqual(testData.Length, entry.Length);
            Assert.AreEqual(1, cache.Size, "Size property was wrong");
        }
Ejemplo n.º 8
0
        public void TestSimpleCacheAndRetrieval()
        {
            var cache = new LRUCache<UUID, String>(MAX_CACHE_SIZE);
            String testData = "Test Data";
            UUID id = UUID.Random();

            cache.Add(id, testData);
            Assert.IsTrue(cache.Contains(id));
            Assert.AreEqual(1, cache.Size);

            String entry;
            Assert.IsTrue(cache.TryGetValue(id, out entry));
            Assert.AreEqual(testData.Length, entry.Length);
            Assert.AreEqual(1, cache.Size);
        }
Ejemplo n.º 9
0
        public void CacheShouldRemoveLeasRecentlyUsedItems()
        {
            var items = new[] {
                KeyValuePair.Create(1, "One"),
                KeyValuePair.Create(3, "Three"),
                KeyValuePair.Create(2, "Two"),
                KeyValuePair.Create(5, "Five"),
                KeyValuePair.Create(4, "Four"),
            };

            ILRUCache <int, string> lruCache = new LRUCache <int, string>(2);

            foreach (var(key, value) in items)
            {
                lruCache.Add(key, value);
            }

            var cacheElements = lruCache.ToArray();

            Assert.AreEqual(2, cacheElements.Length);
            Assert.AreEqual(5, cacheElements[0].Key);
            Assert.AreEqual(4, cacheElements[1].Key);

            lruCache.Lookup(5);
            cacheElements = lruCache.ToArray();
            Assert.AreEqual(2, cacheElements.Length);
            Assert.AreEqual(4, cacheElements[0].Key);
            Assert.AreEqual(5, cacheElements[1].Key);

            for (var i = 1; i <= 3; i++)
            {
                Assert.False(lruCache.Contains(i));
            }
            Assert.True(lruCache.Contains(4));
            Assert.True(lruCache.Contains(5));
        }
Ejemplo n.º 10
0
        public void Test3()
        {
            var random = new Random();
            var cache  = new LRUCache <int, int>(10000);

            for (var i = 0; i < 10000; i++)
            {
                cache.Add(i, i);
            }

            for (var i = 0; i < 1000; i++)
            {
                Assert.True(cache.Contains(random.Next(10000)));
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     格式 [bundle|]asset
        /// </summary>
        /// <param name="assetPath"></param>
        /// <param name="defaultBundle"></param>
        /// <returns></returns>
        public static AssetId Parse(string assetPath, string defaultBundle = null)
        {
            if (_Cache.Contains(assetPath))
            {
                return(_Cache.Get(assetPath));
            }
            if (string.IsNullOrEmpty(assetPath))
            {
                throw AssetPathInvalidException.Default;
            }

            var split = assetPath.Split('|');

            var result = split.Length == 1 ?
                         new AssetId(defaultBundle, split[0]) :
                         new AssetId(split[0], split[1]);

            _Cache.Add(assetPath, result);
            return(result);
        }
Ejemplo n.º 12
0
        public void Test4()
        {
            var random = new Random();
            var cache  = new LRUCache <int, int>(1000000);

            for (var i = 0; i < 1000000; i++)
            {
                cache.Add(random.Next(1000000), i);
            }

            var count = 0;

            for (var i = 0; i < 1000000; i++)
            {
                if (cache.Contains(i))
                {
                    count++;
                }
            }

            Assert.AreEqual(0.632, count / 1000000.0, 0.001);
        }
Ejemplo n.º 13
0
        public void UnloadUnused()
        {
            tmps.Clear();
            int currFrameCount = Time.frameCount;

            foreach (var pair in loaded)
            {
                var info = pair.Value;

                if (refMgr.HasRef(info.asset))
                {
                    continue;
                }

                if (info.unusedFrame == 0)
                {
                    info.unusedFrame = currFrameCount;
                    lruCache.Put(pair.Key);
                }
                if (currFrameCount - info.unusedFrame < 30)
                {
                    continue;
                }

                tmps.Add(pair.Key);
            }

            foreach (var key in tmps)
            {
                if (lruCache.Contains(key))
                {
                    continue;
                }
                Unload(key);
            }
            tmps.Clear();
        }
Ejemplo n.º 14
0
 public bool HasAsset(UUID assetId)
 {
     return(_assetCache.Contains(assetId));
 }