Пример #1
0
        public CacheManager(IRandomAwaiter randomAwaiter, ICacheKeeper cacheKeeper)
        {
            DefaultPicture = new NewPicture(ConfigurationManager.AppSettings["DefaultImage"]);

            _randomAwaiter = randomAwaiter;
            _cacheKeeper   = cacheKeeper;
        }
Пример #2
0
        public Task <NewPicture> GeneratePicture(string uri)
        {
            if (_cacheKeeper.AllCache.Any(x => x.Key == GetFileSize(uri)))
            {
                return(ReturnAlreadyGenerated(uri));
            }

            var key = GetFileSize(uri);

            CancellationTokenSource cts = new CancellationTokenSource();

            var task = Task.Factory.StartNew <NewPicture>
                       (
                ((obj) =>
            {
                _randomAwaiter.ThreadSleep();

                var newPicture = new NewPicture(obj.ToString());

                return(newPicture);
            }),
                uri,
                cts.Token
                       );

            return(Task.Factory.StartNew <NewPicture>(() =>
            {
                if (Task.WaitAll(new[] { task }, TimeSpan.FromSeconds(_cacheKeeper.MaxDownloadingTIme)))
                {
                    var resultPicture = task.Result;

                    _cacheKeeper.AllCache.Add(new KeyValuePair <long, NewPicture>(key, resultPicture));
                }
                else
                {
                    cts.Cancel();

                    _cacheKeeper.AllCache.Add(new KeyValuePair <long, NewPicture>(key, DefaultPicture));
                }

                if (_cacheKeeper.AllCache.Count > _cacheKeeper.MaxCapacity)
                {
                    _cacheKeeper.AllCache.RemoveAt(0);
                }

                return _cacheKeeper.AllCache.Last().Value;
            }));
        }