private async Task RunSemaphoreTestAsync(bool useCacheSyncronization) { using (var harness = base.CreateTestHarness()) { MockHttpManager httpManager = harness.HttpManager; httpManager.AddInstanceDiscoveryMockHandler(); ConfidentialClientApplication app = ConfidentialClientApplicationBuilder.Create(TestConstants.ClientId) .WithClientSecret(TestConstants.ClientSecret) .WithAuthority(TestConstants.AuthorityUtidTenant) .WithCacheSynchronization(useCacheSyncronization) .WithHttpManager(httpManager) .BuildConcrete(); httpManager.AddMockHandlerSuccessfulClientCredentialTokenResponseMessage(); BlockingCache inMemoryTokenCache = new BlockingCache(); inMemoryTokenCache.Bind(app.AppTokenCache); // Seed the cache with a token var result = await app.AcquireTokenForClient(TestConstants.s_scope.ToArray()) .ExecuteAsync() .ConfigureAwait(false); Assert.IsTrue(result.AuthenticationResultMetadata.TokenSource == TokenSource.IdentityProvider); var blockingTask = RunAsync(inMemoryTokenCache, app, true); var nonBlockingTask1 = RunAsync(inMemoryTokenCache, app, false); var nonBlockingTask2 = RunAsync(inMemoryTokenCache, app, false); int res = Task.WaitAny(new[] { blockingTask, nonBlockingTask1, nonBlockingTask2 }, 100); if (useCacheSyncronization) { Assert.AreEqual(-1, res, "WaitAny should have timed out, all tasks are blocked when the first call is blocking"); } else { Assert.AreNotEqual(-1, res, "WaitAny should have NOT timed out, the 2 non-blocking tasks should be allowed to complete"); Assert.IsTrue(nonBlockingTask1.IsCompleted); Assert.IsTrue(nonBlockingTask2.IsCompleted); Assert.IsFalse(blockingTask.IsCompleted, "The blocking task should still be blocked"); Assert.IsTrue(nonBlockingTask1.Result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); Assert.IsTrue(nonBlockingTask2.Result.AuthenticationResultMetadata.TokenSource == TokenSource.Cache); } } }
private static async Task <AuthenticationResult> RunAsync(BlockingCache cache, IConfidentialClientApplication app, bool block = false) { cache.BlockAccess = block; return(await app.AcquireTokenForClient(TestConstants.s_scope.ToArray()).ExecuteAsync().ConfigureAwait(false)); }