コード例 #1
0
 public ChangeTokenInfo(
     CancellationTokenSource tokenSource,
     CancellationChangeToken changeToken)
 {
     TokenSource = tokenSource;
     ChangeToken = changeToken;
 }
コード例 #2
0
        public Task DoWorkAsync(IServiceProvider serviceProvider, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogDebug("Trying my hands on logging & background task!");

                var injectedService = serviceProvider.GetService <SomeUsefulService>();

                var x = Task.FromResult(injectedService.SomeMethod());

                var y = Task.FromResult(injectedService.SomeIterativeMethod().GetAsyncEnumerator(cancellationToken));
                CancellationTokenSource cts          = new CancellationTokenSource(TimeSpan.FromSeconds(30));
                var          xx                      = cts.Token;
                IChangeToken cancellationChangeToken = new CancellationChangeToken(cancellationToken);
                var          z = Task <int> .Factory.StartNew(() => injectedService.SomeMethod(), cancellationToken);

                return(null);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "some error occured!!");
                return(null);
                //throw;
            }
            //throw new NotImplementedException();
        }
コード例 #3
0
        public void Foo()
        {
            var item = new object();

            //absolute expiration using TimeSpan
            _cache.Set("key", item, TimeSpan.FromDays(1));

            //absolute expiration using DateTime
            _cache.Set("key", item, new DateTime(2020, 1, 1));

            //sliding expiration (evict if not accessed for 7 days)
            _cache.Set("key", item, new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromDays(7)
            });

            //use both absolute and sliding expiration
            _cache.Set("key", item, new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30),
                SlidingExpiration = TimeSpan.FromDays(7)
            });

            // use a cancellation token
            var tokenSource = new CancellationTokenSource();

            var token = new CancellationChangeToken(tokenSource.Token);

            _cache.Set("key", item, new MemoryCacheEntryOptions().AddExpirationToken(token));
        }
コード例 #4
0
        public override bool Add(BlobStoreData data, out string key)
        {
            lock (Cache)
            {
                key = shortid.ShortId.Generate(useNumbers: true, useSpecial: false, length: 6);

                double cacheExpirationInMinutes = 120; // TODO: Make expiration configurable - global config vs Endpoint specific config

                DateTime expiryDate = DateTime.Now.AddMinutes(cacheExpirationInMinutes);

                var expirationToken = new CancellationChangeToken(
                    new CancellationTokenSource(TimeSpan.FromMinutes(cacheExpirationInMinutes + 0.1)).Token); // cancellation token is necessary to force Post Eviction Callback to call on time

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        .SetPriority(CacheItemPriority.NeverRemove)
                                        .AddExpirationToken(expirationToken)
                                        .SetAbsoluteExpiration(expiryDate)
                                        .RegisterPostEvictionCallback(callback: OnCacheItemExpired, state: this);

                data.ExpiryDate = expiryDate;
                data.Ref        = key;

                BlobStore.Cache.Set <BlobStoreData>(key, data, cacheEntryOptions);
                CacheKeys.Add(key);

                Interlocked.Increment(ref _totalItemsInCache);

                data.Size           = (data.Data?.Length ?? 0) + (data.ContentType?.Length ?? 0) + (data.Filename?.Length ?? 0);
                _totalBytesInCache += data.Size;

                return(true);
            }
        }
コード例 #5
0
    public void ExpiryTests(string key)
    {
        using IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

        var times = new List <DateTime>();

        using var cts = new CancellationTokenSource(millisecondsDelay: 10_000);

        while (!cts.IsCancellationRequested)
        {
            if (!cache.TryGetValue(key, out DateTime time))
            {
                time = DateTime.UtcNow;

                var a           = new CancellationTokenSource(millisecondsDelay: 1_000);
                var changeToken = new CancellationChangeToken(a.Token);

                var options = new MemoryCacheEntryOptions()
                              .AddExpirationToken(changeToken);

                cache.Set(key, time, options);
            }

            times.Add(time);
            Thread.Sleep(millisecondsTimeout: 200);
        }

        var grouped = times.GroupBy(ts => ts).ToList();

        Assert.InRange(grouped.Count, 9, 11);
        Assert.All(grouped, g => Assert.InRange(g.Count(), 1, 6));
    }
コード例 #6
0
    public void Endpoints_ChangeTokenTriggered_EndpointsRecreated()
    {
        // Arrange
        var actionDescriptorCollectionProviderMock = new Mock <ActionDescriptorCollectionProvider>();

        actionDescriptorCollectionProviderMock
        .Setup(m => m.ActionDescriptors)
        .Returns(new ActionDescriptorCollection(new[]
        {
            CreateActionDescriptor(new { controller = "TestController", action = "TestAction" }, "/test")
        }, version: 0));

        CancellationTokenSource cts = null;

        actionDescriptorCollectionProviderMock
        .Setup(m => m.GetChangeToken())
        .Returns(() =>
        {
            cts             = new CancellationTokenSource();
            var changeToken = new CancellationChangeToken(cts.Token);

            return(changeToken);
        });

        var dataSource = CreateDataSource(actionDescriptorCollectionProviderMock.Object);

        // Act
        var endpoints = dataSource.Endpoints;

        Assert.Collection(endpoints,
                          (e) =>
        {
            var routePattern = Assert.IsType <RouteEndpoint>(e).RoutePattern;
            Assert.Equal("/test", routePattern.RawText);
            Assert.Equal("TestController", routePattern.RequiredValues["controller"]);
            Assert.Equal("TestAction", routePattern.RequiredValues["action"]);
        });

        actionDescriptorCollectionProviderMock
        .Setup(m => m.ActionDescriptors)
        .Returns(new ActionDescriptorCollection(new[]
        {
            CreateActionDescriptor(new { controller = "NewTestController", action = "NewTestAction" }, "/test")
        }, version: 1));

        cts.Cancel();

        // Assert
        var newEndpoints = dataSource.Endpoints;

        Assert.NotSame(endpoints, newEndpoints);
        Assert.Collection(newEndpoints,
                          (e) =>
        {
            var routePattern = Assert.IsType <RouteEndpoint>(e).RoutePattern;
            Assert.Equal("/test", routePattern.RawText);
            Assert.Equal("NewTestController", routePattern.RequiredValues["controller"]);
            Assert.Equal("NewTestAction", routePattern.RequiredValues["action"]);
        });
    }
        /// <inheritdoc />
        /// <summary>
        /// Initializes a new instance with the specified source.
        /// </summary>
        /// <param name="source">The <see cref="IConfigurationSource"/> used to retrieve values from AWS Systems Manager Parameter Store</param>
        /// <param name="systemsManagerProcessor">The <see cref="ISystemsManagerProcessor"/> used to retrieve values from AWS Systems Manager Parameter Store</param>
        public SystemsManagerConfigurationProvider(SystemsManagerConfigurationSource source, ISystemsManagerProcessor systemsManagerProcessor)
        {
            Source = source ?? throw new ArgumentNullException(nameof(source));
            SystemsManagerProcessor = systemsManagerProcessor ?? throw new ArgumentNullException(nameof(systemsManagerProcessor));

            if (source.AwsOptions == null)
            {
                throw new ArgumentNullException(nameof(source.AwsOptions));
            }
            if (source.Path == null)
            {
                throw new ArgumentNullException(nameof(source.Path));
            }

            if (source.ReloadAfter != null)
            {
                ChangeToken.OnChange(() =>
                {
                    var cancellationTokenSource = new CancellationTokenSource(source.ReloadAfter.Value);
                    var cancellationChangeToken = new CancellationChangeToken(cancellationTokenSource.Token);
                    return(cancellationChangeToken);
                }, async() =>
                {
                    ReloadTaskEvent.Reset();
                    try
                    {
                        await LoadAsync(true).ConfigureAwait(false);
                    }
                    finally
                    {
                        ReloadTaskEvent.Set();
                    }
                });
            }
        }
コード例 #8
0
        public IChangeToken CreateChangeToken()
        {
            _cts = new CancellationTokenSource();
            var ct = new CancellationChangeToken(_cts.Token);

            return(ct);
        }
コード例 #9
0
        private IChangeToken GetOrAddWildcardChangeToken(string pattern)
        {
            ChangeTokenInfo tokenInfo;

            if (!_wildcardTokenLookup.TryGetValue(pattern, out tokenInfo))
            {
                var cancellationTokenSource = new CancellationTokenSource();
                var cancellationChangeToken = new CancellationChangeToken(cancellationTokenSource.Token);
                var matcher = new Matcher(StringComparison.OrdinalIgnoreCase);
                matcher.AddInclude(pattern);
                tokenInfo = new ChangeTokenInfo(cancellationTokenSource, cancellationChangeToken, matcher);
                tokenInfo = _wildcardTokenLookup.GetOrAdd(pattern, tokenInfo);
            }

            IChangeToken changeToken = tokenInfo.ChangeToken;

            if (_pollForChanges)
            {
                // The expiry of CancellationChangeToken is controlled by this type and consequently we can cache it.
                // PollingFileChangeToken on the other hand manages its own lifetime and consequently we cannot cache it.
                changeToken = new CompositeChangeToken(
                    new[]
                {
                    changeToken,
                    new PollingWildCardChangeToken(_root, pattern)
                });
            }

            return(changeToken);
        }
コード例 #10
0
        private IChangeToken GetOrAddFilePathChangeToken(string filePath)
        {
            ChangeTokenInfo tokenInfo;

            if (!_filePathTokenLookup.TryGetValue(filePath, out tokenInfo))
            {
                var cancellationTokenSource = new CancellationTokenSource();
                var cancellationChangeToken = new CancellationChangeToken(cancellationTokenSource.Token);
                tokenInfo = new ChangeTokenInfo(cancellationTokenSource, cancellationChangeToken);
                tokenInfo = _filePathTokenLookup.GetOrAdd(filePath, tokenInfo);
            }

            IChangeToken changeToken = tokenInfo.ChangeToken;

            if (_pollForChanges)
            {
                // The expiry of CancellationChangeToken is controlled by this type and consequently we can cache it.
                // PollingFileChangeToken on the other hand manages its own lifetime and consequently we cannot cache it.
                changeToken = new CompositeChangeToken(
                    new[]
                {
                    changeToken,
                    new PollingFileChangeToken(new FileInfo(Path.Combine(_root, filePath)))
                });
            }

            return(changeToken);
        }
コード例 #11
0
        public static Func <IChangeToken> UseCallbackRegistrations(Func <Action, IDisposable> registerListener)
        {
            IDisposable         previousRegistration = null;
            Func <IChangeToken> changeTokenFactory   = () =>
            {
                // When should ensure any previous CancellationTokenSource is disposed,
                // and we remove old monitor OnChange listener, before creating new ones.
                previousRegistration?.Dispose();

                var changeTokenSource = new CancellationTokenSource();
                var disposable        = registerListener(() => changeTokenSource.Cancel());

                previousRegistration = new InvokeOnDispose(() =>
                {
                    // Ensure disposal of listener and token source that we created.
                    disposable.Dispose();
                    changeTokenSource.Dispose();
                });

                var changeToken = new CancellationChangeToken(changeTokenSource.Token);
                return(changeToken);
            };

            return(changeTokenFactory);
        }
コード例 #12
0
        internal IChangeToken GetOrAddFilePathChangeToken(string filePath)
        {
            if (!_filePathTokenLookup.TryGetValue(filePath, out var tokenInfo))
            {
                var cancellationTokenSource = new CancellationTokenSource();
                var cancellationChangeToken = new CancellationChangeToken(cancellationTokenSource.Token);
                tokenInfo = new ChangeTokenInfo(cancellationTokenSource, cancellationChangeToken);
                tokenInfo = _filePathTokenLookup.GetOrAdd(filePath, tokenInfo);
            }

            IChangeToken changeToken = tokenInfo.ChangeToken;

            if (PollForChanges)
            {
                // The expiry of CancellationChangeToken is controlled by this type and consequently we can cache it.
                // PollingFileChangeToken on the other hand manages its own lifetime and consequently we cannot cache it.
                var pollingChangeToken = new PollingFileChangeToken(new FileInfo(Path.Combine(_root, filePath)));

                if (UseActivePolling)
                {
                    pollingChangeToken.ActiveChangeCallbacks   = true;
                    pollingChangeToken.CancellationTokenSource = new CancellationTokenSource();
                    PollingChangeTokens.TryAdd(pollingChangeToken, pollingChangeToken);
                }

                changeToken = new CompositeChangeToken(
                    new[]
                {
                    changeToken,
                    pollingChangeToken,
                });
            }

            return(changeToken);
        }
コード例 #13
0
        public async Task <ActionResponse <T> > SetInCache <T>(T cachedObject)
        {
            try
            {
                var expirationTime  = DateTime.Now.AddMinutes(expirationMinutes);
                var expirationToken = new CancellationChangeToken(
                    new CancellationTokenSource(TimeSpan.FromMinutes(expirationMinutes + .01))
                    .Token);

                var objectType = cachedObject.GetType();
                var attribute  = objectType.GenericTypeArguments[0].GetCustomAttributes(typeof(Cached), true).FirstOrDefault() as Cached;

                MemoryCacheEntryOptions cacheOptions = new MemoryCacheEntryOptions()
                                                       .SetPriority(CacheItemPriority.High)
                                                       .SetAbsoluteExpiration(expirationTime)
                                                       .AddExpirationToken(expirationToken)
                                                       .RegisterPostEvictionCallback(callback: RefreshCache <T>, state: this);

                memoryCache.Set(attribute.Key, cachedObject);
                return(await ActionResponse <T> .ReturnSuccess());
            }
            catch (Exception)
            {
                return(await ActionResponse <T> .ReturnError("Greška prilikom postavljanja podataka u cache."));
            }
        }
コード例 #14
0
        public IEnumerable <FeaturedMovies> GetFeaturedMovies(out IChangeToken expirationToken)
        {
            _featuredMoviesTokenSource = new CancellationTokenSource();

            expirationToken = new CancellationChangeToken(_featuredMoviesTokenSource.Token);
            return(GetMovies().OrderBy(m => m.Rank).Take(2));
        }
コード例 #15
0
        /// <summary>
        /// Gets a parameter from cache using the key value
        /// Returns a <see cref="Result"/> wrapping a: <see cref="Parameter"/>.
        ///If something bad happens (<see cref="ResultBase.IsFailed"/>), you have to use <see cref="ResultBase.HasError(Func{Error, bool})"/> to get the following errors: <see cref="ParameterNotFoundError"/> or <see cref="FetchingParameterError"/>
        /// </summary>
        /// <param name="id">External product id</param>
        public async Task <Result <Parameter> > GetParameterAsync(string key)
        {
            try
            {
                var parameters = await
                                 memoryCache.GetOrCreateAsync(PARAMETERS_KEY, entry =>
                {
                    entry.SlidingExpiration = TimeSpan.FromSeconds(3);
                    // set item with token expiration and callback
                    TimeSpan expirationMinutes = System.TimeSpan.FromMinutes(EXPIRATION_MINUTES);
                    var expirationTime         = DateTime.Now.Add(expirationMinutes);
                    var expirationToken        = new CancellationChangeToken(
                        new CancellationTokenSource(TimeSpan.FromMinutes(EXPIRATION_MINUTES)).Token);
                    entry
                    // Pin to cache.
                    .SetPriority(Microsoft.Extensions.Caching.Memory.CacheItemPriority.Normal)
                    // Set the actual expiration time
                    .SetAbsoluteExpiration(expirationTime)
                    // Force eviction to run
                    .AddExpirationToken(expirationToken)
                    // Add eviction callback
                    .RegisterPostEvictionCallback(callback: CacheItemRemoved);
                    return(GetParametersFromDb());
                });

                var parameter = parameters.FirstOrDefault(p => p.Key == key);

                return(parameter == default ? Result.Fail(new ParameterNotFoundError($"Parameter not found with key: {key}", key)).Log() : Result.Ok(parameter));
            }
            catch (Exception e)
            {
                return(Result.Fail(new FetchingParameterError("Error fetching parameters: " + e.Message).CausedBy(e)).Log());
            }
        }
        /// <summary>
        /// Adds <see cref="ReloadPipelineMiddleware"/> to the middleware pipeline, with a change token to invalidate it and rebuild it whenever <typeparamref name="TOptions"/> changes.
        /// </summary>
        /// <typeparam name="TOptions"></typeparam>
        /// <param name="builder"></param>
        /// <param name="configure"></param>
        /// <param name="isTerminal"></param>
        /// <returns></returns>
        /// <remarks>You must ensure <typeparamref name="TOptions"/></remarks> has been registered with the options system in ConfigureServices.
        private static IApplicationBuilder AddReloadablePipeline <TOptions>(this IApplicationBuilder builder, Action <IApplicationBuilder, IWebHostEnvironment, TOptions> configure, bool isTerminal)
            where TOptions : class
        {
            var env     = builder.ApplicationServices.GetRequiredService <IWebHostEnvironment>();
            var monitor = builder.ApplicationServices.GetRequiredService <IOptionsMonitor <TOptions> >();

            IDisposable previousRegistration = null;

            var factory = new RequestDelegateFactory(env, () =>
            {
                // When should ensure any previous CancellationTokenSource is disposed,
                // and we remove old monitor OnChange listener, before creating new ones.
                previousRegistration?.Dispose();

                var changeTokenSource = new CancellationTokenSource();
                var monitorListener   = monitor.OnChange(a => changeTokenSource.Cancel());

                previousRegistration = new InvokeOnDispose(() =>
                {
                    // Ensure disposal of listener and token source that we created.
                    monitorListener.Dispose();
                    changeTokenSource.Dispose();
                });

                var changeToken = new CancellationChangeToken(changeTokenSource.Token);
                return(changeToken);
            }, (a, b) =>
            {
                configure(a, b, monitor.CurrentValue);
            });

            builder.UseMiddleware <ReloadPipelineMiddleware>(builder, factory, isTerminal);
            return(builder);
        }
コード例 #17
0
        public void NotifyChanges()
        {
            var old = Interlocked.Exchange(ref _source, new CancellationTokenSource());

            _token = new CancellationChangeToken(_source.Token);
            old.Cancel();
        }
コード例 #18
0
ファイル: UnitTest10.cs プロジェクト: wwwK/Ray.EssayNotes.DDD
 public B(CancellationChangeToken cct)
 {
     cct.RegisterChangeCallback(obj =>
     {
         Debug.WriteLine("B接收到了事件");
     },
                                "test");
 }
コード例 #19
0
 public ChangeTokenInfo(
     CancellationTokenSource tokenSource,
     CancellationChangeToken changeToken,
     Matcher?matcher)
 {
     TokenSource = tokenSource;
     ChangeToken = changeToken;
     Matcher     = matcher;
 }
コード例 #20
0
        public void Endpoints_ChangeTokenTriggered_EndpointsRecreated()
        {
            // Arrange
            var actionDescriptorCollectionProviderMock = new Mock <IActionDescriptorCollectionProvider>();

            actionDescriptorCollectionProviderMock
            .Setup(m => m.ActionDescriptors)
            .Returns(new ActionDescriptorCollection(new[]
            {
                CreateActionDescriptor(new { controller = "TestController", action = "TestAction" })
            }, version: 0));

            CancellationTokenSource cts = null;

            var changeProviderMock = new Mock <IActionDescriptorChangeProvider>();

            changeProviderMock.Setup(m => m.GetChangeToken()).Returns(() =>
            {
                cts             = new CancellationTokenSource();
                var changeToken = new CancellationChangeToken(cts.Token);

                return(changeToken);
            });

            var dataSource = CreateMvcEndpointDataSource(
                actionDescriptorCollectionProviderMock.Object,
                actionDescriptorChangeProviders: new[] { changeProviderMock.Object });

            dataSource.ConventionalEndpointInfos.Add(CreateEndpointInfo(
                                                         string.Empty,
                                                         "{controller}/{action}",
                                                         new RouteValueDictionary(new { action = "TestAction" })));

            // Act
            var endpoints = dataSource.Endpoints;

            Assert.Collection(endpoints,
                              (e) => Assert.Equal("TestController", Assert.IsType <RouteEndpoint>(e).RoutePattern.RawText),
                              (e) => Assert.Equal("TestController/TestAction", Assert.IsType <RouteEndpoint>(e).RoutePattern.RawText));

            actionDescriptorCollectionProviderMock
            .Setup(m => m.ActionDescriptors)
            .Returns(new ActionDescriptorCollection(new[]
            {
                CreateActionDescriptor(new { controller = "NewTestController", action = "NewTestAction" })
            }, version: 1));

            cts.Cancel();

            // Assert
            var newEndpoints = dataSource.Endpoints;

            Assert.NotSame(endpoints, newEndpoints);
            Assert.Collection(newEndpoints,
                              (e) => Assert.Equal("NewTestController/NewTestAction", Assert.IsType <RouteEndpoint>(e).RoutePattern.RawText));
        }
コード例 #21
0
        public override IChangeToken GetChangeToken()
        {
            if (_cts == null)
            {
                _cts = new CancellationTokenSource();
                _cct = new CancellationChangeToken(_cts.Token);
            }

            return(_cct);
        }
コード例 #22
0
ファイル: UnitTest10.cs プロジェクト: wwwK/Ray.EssayNotes.DDD
        public void Test1()
        {
            var cts = new CancellationTokenSource();
            var cct = new CancellationChangeToken(cts.Token);

            var a = new A(cts);
            var b = new B(cct);

            Console.ReadLine();
        }
コード例 #23
0
        public static Func <IChangeToken> UseCancellationTokens(Func <CancellationToken> cancellationTokenFactory)
        {
            Func <IChangeToken> changeTokenFactory = () =>
            {
                var token       = cancellationTokenFactory();
                var changeToken = new CancellationChangeToken(token);
                return(changeToken);
            };

            return(changeTokenFactory);
        }
コード例 #24
0
ファイル: Signal.cs プロジェクト: china-live/OCore
 public IChangeToken GetToken(string key)
 {
     return(_changeTokens.GetOrAdd(
                key,
                _ =>
     {
         var cancellationTokenSource = new CancellationTokenSource();
         var changeToken = new CancellationChangeToken(cancellationTokenSource.Token);
         return new ChangeTokenInfo(changeToken, cancellationTokenSource);
     }).ChangeToken);
 }
コード例 #25
0
        public StaticConfig()
        {
            ChangeToken = new CancellationChangeToken(_cts.Token);
            var cluster1 = new Cluster()
            {
                Id = "cluster1"
            };

            cluster1.Destinations.Add("cluster1/destination1", new Destination()
            {
                Address = @"http://127.0.0.1:4000"
            });
            var cluster2 = new Cluster()
            {
                Id = "cluster2"
            };

            cluster2.Destinations.Add("cluster2/destination1", new Destination()
            {
                Address = @"http://127.0.0.1:3000"
            });
            _clusters = new List <Cluster>();
            _clusters.Add(cluster1);
            _clusters.Add(cluster2);


            var route1 = new ProxyRoute()
            {
                RouteId   = "route1",
                ClusterId = "cluster1"
            };

            route1.Transforms = new List <IDictionary <string, string> >();
            route1.Transforms.Add(new Dictionary <string, string>()
            {
                { "PathRemovePrefix", "/app" }
            });
            route1.Match.Path = "/app";
            var route2 = new ProxyRoute()
            {
                RouteId   = "route2",
                ClusterId = "cluster2"
            };

            route2.Transforms = new List <IDictionary <string, string> >();
            route2.Transforms.Add(new Dictionary <string, string>()
            {
                { "PathRemovePrefix", "/status" }
            });
            route2.Match.Path = "/status";
            _routes           = new List <ProxyRoute>();
            _routes.Add(route1);
            _routes.Add(route2);
        }
コード例 #26
0
    private IChangeToken GetOrAddChangeToken(string filePath)
    {
        if (!FilePathTokenLookup.TryGetValue(filePath, out var tokenInfo))
        {
            var cancellationTokenSource = new CancellationTokenSource();
            var cancellationChangeToken = new CancellationChangeToken(cancellationTokenSource.Token);
            tokenInfo = new ChangeTokenInfo(cancellationTokenSource, cancellationChangeToken);
            tokenInfo = FilePathTokenLookup.GetOrAdd(filePath, tokenInfo);
        }

        return(tokenInfo.ChangeToken);
    }
コード例 #27
0
        private void ManageCacheWithDependencies()
        {
            // Items can also be expired from the cache as a result of a dependency
            var cancellationTokenSource = new CancellationTokenSource();
            var changeToken             = new CancellationChangeToken(cancellationTokenSource.Token); // CompositeChangeToken
            var options = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(20)).AddExpirationToken(changeToken);

            _cache.Set("MyKey5", "Value", options);

            //cancellationTokenSource.Cancel();
            //changeToken.HasChanged
        }
コード例 #28
0
        public void TryGet_ValueIsExpired_ReturnsFalse()
        {
            const string key         = "key";
            var          tokenSource = new CancellationTokenSource();
            var          cancelToken = new CancellationChangeToken(tokenSource.Token);

            _memoryCache.Set(key, "cachedString", cancelToken);
            tokenSource.Cancel();

            var result = _cacheManager.TryGet <string>(key, out _);

            Assert.False(result);
        }
コード例 #29
0
 private async Task <List <RankingListRow> > GetRankingListCached(CancellationToken cancellationToken) => await _memoryCache.GetOrCreateAsync(
     string.Join("_", _tenantContext.Identifier, typeof(Ranking).FullName, nameof(RankingListRow)),
     cache =>
 {
     cache.AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30);
     var tokenSource = new CancellationTokenSource();
     var token       = new CancellationChangeToken(tokenSource.Token);
     cache.AddExpirationToken(token);
     return(_appDb.RankingRepository.GetRankingListAsync(
                new PredicateExpression(RankingListFields.TournamentIsComplete == true),
                cancellationToken));
 }
     );
コード例 #30
0
ファイル: CacheDependency.cs プロジェクト: turenc/Plato
 public IChangeToken GetToken(string key)
 {
     return(_dependencies.GetOrAdd(key, _ =>
     {
         var cancellationToken = new CancellationTokenSource();
         var changeToken = new CancellationChangeToken(cancellationToken.Token);
         return new CacheDependencyInfo()
         {
             ChangeToken = changeToken,
             CancellationToken = cancellationToken
         };
     }).ChangeToken);
 }