public async Task Should_honour_cancellation_even_if_prior_execution_has_cached() { const string valueToReturn = "valueToReturn"; const string executionKey = "SomeExecutionKey"; CachePolicy cache = Policy.CacheAsync(new StubCacheProvider(), TimeSpan.MaxValue); CancellationTokenSource tokenSource = new CancellationTokenSource(); int delegateInvocations = 0; Func <CancellationToken, Task <string> > func = async ct => { // delegate does not observe cancellation token; test is whether CacheEngine does. delegateInvocations++; await TaskHelper.EmptyTask.ConfigureAwait(false); return(valueToReturn); }; (await cache.ExecuteAsync(func, new Context(executionKey), tokenSource.Token).ConfigureAwait(false)).Should().Be(valueToReturn); delegateInvocations.Should().Be(1); tokenSource.Cancel(); cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(executionKey), tokenSource.Token)) .ShouldThrow <OperationCanceledException>(); delegateInvocations.Should().Be(1); }
public async Task Should_honour_cancellation_during_delegate_execution_and_not_put_to_cache() { const string valueToReturn = "valueToReturn"; const string executionKey = "SomeExecutionKey"; IAsyncCacheProvider stubCacheProvider = new StubCacheProvider(); CachePolicy cache = Policy.CacheAsync(stubCacheProvider, TimeSpan.MaxValue); CancellationTokenSource tokenSource = new CancellationTokenSource(); Func <CancellationToken, Task <string> > func = async ct => { tokenSource.Cancel(); // simulate cancellation raised during delegate execution ct.ThrowIfCancellationRequested(); await TaskHelper.EmptyTask.ConfigureAwait(false); return(valueToReturn); }; cache.Awaiting(policy => policy.ExecuteAsync(func, new Context(executionKey), tokenSource.Token)) .ShouldThrow <OperationCanceledException>(); ((string)await stubCacheProvider.GetAsync(executionKey, CancellationToken.None, false).ConfigureAwait(false)).Should().BeNull(); }