Example #1
0
        public async Task When_Test(
            bool useCancellation,
            bool useWhenAllCompleteAction)
        {
            var            cancellation          = useCancellation ? new CancellationTokenSource() : null;
            var            disposed              = new ManualResetEventSlim(false);
            Action <int[]> whenAllCompleteAction = null;

            if (useWhenAllCompleteAction)
            {
                whenAllCompleteAction = DisposeCancellation;
            }
            using (await _gate.AcquireAsync())
            {
                // arrange
                var          sw    = Stopwatch.StartNew();
                Task <int>[] tasks =
                {
                    Delayed(TimeSpan.FromMilliseconds(1)),
                    Delayed(TimeSpan.FromMilliseconds(50)),
                    Delayed(TimeSpan.FromMilliseconds(100)),
                    Delayed(TimeSpan.FromMilliseconds(200))
                };


                // act
                (int result, bool succeed) = await tasks.When(
                    x => x != 1,
                    cancellation,
                    whenAllCompleteAction);

                // assert
                sw.Stop();
                TimeSpan duration = sw.Elapsed;
                if (cancellation != null)
                {
                    Assert.IsTrue(cancellation.IsCancellationRequested, "Cancellation");
                }
                Assert.IsTrue(duration >= TimeSpan.FromMilliseconds(50) &&
                              duration < TimeSpan.FromMilliseconds(100), "Duration");
                Assert.IsTrue(succeed, "Succeed");
                Assert.AreEqual(1, result);
                if (whenAllCompleteAction != null)
                {
                    Assert.IsTrue(disposed.Wait(500), "DisposeCancellation");
                }
            }
            void DisposeCancellation(int[] _)
            {
                cancellation?.Dispose();
                disposed.Set();
            }

            async Task <int> Delayed(TimeSpan time)
            {
                await Task.Delay(time).ConfigureAwait(false);

                return((int)time.TotalMilliseconds);
            }
        }
Example #2
0
        public async Task Should_throw_oce_if_cancelled()
        {
            using var mutex = new AsyncLock();
            using var cts   = new CancellationTokenSource();

            using var releaser = await mutex.AcquireAsync(cts.Token).ConfigureAwait(false);

            cts.CancelAfter(50);

            await Assert.ThrowsAnyAsync <OperationCanceledException>(
                () => mutex.AcquireAsync(cts.Token)
                ).ConfigureAwait(false);
        }
Example #3
0
 public static async Task AsyncLock_AcquireAsync_Timeout_Timespan()
 {
     using (var l = new AsyncLock())
     {
         var sw = Stopwatch.StartNew();
         using (AsyncLockCookie t1 = await l.AcquireAsync())
             using (AsyncLockCookie t2 = await l.AcquireAsync(TimeSpan.FromMilliseconds(100)))
             {
                 Assert.True(t1.IsAcquired);
                 Assert.False(t2.IsAcquired);
                 Assert.True(sw.Elapsed.TotalMilliseconds >= 80);
             }
     }
 }
Example #4
0
 public static async Task AsyncLock_AcquireAsync_Twice()
 {
     using (var l = new AsyncLock())
     {
         using (AsyncLockCookie t = await l.AcquireAsync())
         {
             Assert.True(t.IsAcquired);
             Assert.Equal(t.IsAcquired, t);
         }
         using (AsyncLockCookie t = await l.AcquireAsync())
         {
             Assert.True(t.IsAcquired);
         }
     }
 }
Example #5
0
        public void TestSynchronizeTwoParallelTasks()
        {
            this.TestWithError(async() =>
            {
                SharedEntry entry = new SharedEntry();
                AsyncLock mutex   = AsyncLock.Create();

                async Task WriteAsync(int value)
                {
                    using (await mutex.AcquireAsync())
                    {
                        entry.Value = value;
                    }
                }

                Task task1 = Task.Run(async() =>
                {
                    await WriteAsync(3);
                });

                Task task2 = Task.Run(async() =>
                {
                    await WriteAsync(5);
                });

                await Task.WhenAll(task1, task2);
                AssertSharedEntryValue(entry, 5);
            },
                               configuration: this.GetConfiguration().WithTestingIterations(200),
                               expectedError: "Value is 3 instead of 5.",
                               replay: true);
        }
Example #6
0
        public static TokenFactory GetAccessTokenFactory(
            [NotNull] this RsdnApiAuthenticator authenticator,
            [NotNull] string login,
            [NotNull] string password)
        {
            Code.NotNull(authenticator, nameof(authenticator));

            AuthTokenResponse token = null;
            var tokenLock           = new AsyncLock();

            return(async ct =>
            {
                if (token != null && token.ExpiresOn >= DateTimeOffset.UtcNow)
                {
                    return token.AccessToken;
                }
                using (await tokenLock.AcquireAsync(ct))
                    if (token == null || token.ExpiresOn < DateTimeOffset.UtcNow)
                    {
                        token = token == null
                                                        ? await authenticator.GetTokenByPasswordAsync(login, password, ct)
                                                        : await authenticator.RefreshTokenAsync(token.RefreshToken, ct)
                                ?? await authenticator.GetTokenByPasswordAsync(login, password, ct);
                    }
                return token.AccessToken;
            });
        }
Example #7
0
        public static TokenFactory GetAccessTokenFactory(
            [NotNull] this RsdnApiAuthenticator authenticator,
            [NotNull] Func <AuthTokenResponse> getToken,
            [NotNull] Action <AuthTokenResponse> setToken)
        {
            Code.NotNull(authenticator, nameof(authenticator));

            var tokenLock = new AsyncLock();

            return(async ct =>
            {
                var token = getToken();
                if (token == null)
                {
                    return null;
                }
                if (token.ExpiresOn >= DateTimeOffset.UtcNow)
                {
                    return token.AccessToken;
                }
                using (await tokenLock.AcquireAsync(ct))
                    if (token.ExpiresOn < DateTimeOffset.UtcNow)
                    {
                        token = await authenticator.RefreshTokenAsync(token.RefreshToken, ct);

                        setToken(token);
                    }
                return token?.AccessToken;
            });
        }
Example #8
0
        private static async Task <bool> TryTakeAndHold(
            AsyncLock asyncLock,
            TimeSpan holdTime,
            CancellationToken cancellation = default,
            Action callback = null)
        {
            try
            {
                using (await asyncLock.AcquireAsync(holdTime, cancellation))
                {
                    callback?.Invoke();
                    await TaskEx.Delay(holdTime);
                }

                return(true);
            }
            catch (OperationCanceledException)
            {
                return(false);
            }
            catch (TimeoutException)
            {
                return(false);
            }
        }
Example #9
0
 public void TestAcquireTwice()
 {
     this.TestWithError(async() =>
     {
         AsyncLock mutex = AsyncLock.Create();
         await mutex.AcquireAsync();
         await Task.Run(async() =>
         {
             await mutex.AcquireAsync();
         });
     },
                        expectedError: "Deadlock detected. Task() and Task() are waiting for a task to complete, but no other " +
                        "controlled tasks are enabled. Task() is waiting to acquire a resource that is already " +
                        "acquired, but no other controlled tasks are enabled.",
                        replay: true);
 }
Example #10
0
        public async Task When_Test_All(
            bool useCancellation)
        {
            var cancellation = useCancellation ? new CancellationTokenSource() : default;

            using (await _gate.AcquireAsync())
            {
                // arrange
                var          sw    = Stopwatch.StartNew();
                Task <int>[] tasks =
                {
                    Delayed(TimeSpan.FromMilliseconds(1)),
                    Delayed(TimeSpan.FromMilliseconds(50)),
                    Delayed(TimeSpan.FromMilliseconds(100)),
                    Delayed(TimeSpan.FromMilliseconds(200))
                };


                // act
                (int result, bool succeed, Task <int[]> all) = await tasks.When(
                    x => x != 1,
                    cancellation);

                // assert
                sw.Stop();
                TimeSpan duration = sw.Elapsed;
                if (cancellation != null)
                {
                    Assert.True(cancellation.IsCancellationRequested, "Cancellation");
                }
                Assert.True(duration >= TimeSpan.FromMilliseconds(45) &&
                            duration < TimeSpan.FromMilliseconds(100), "Duration");
                Assert.True(succeed, "Succeed");
                Assert.Equal(50, result);
                await all.WithTimeout(TimeSpan.FromSeconds(10)).ConfigureAwait(false);

                cancellation?.Dispose();
            }

            async Task <int> Delayed(TimeSpan time)
            {
                await Task.Delay(time).ConfigureAwait(false);

                return((int)time.TotalMilliseconds);
            }
        }
Example #11
0
        public async Task Enqueue(T item, string taskName)
        {
            _logger.Mark(taskName, StateEnum.SemaphoreWait);
            await _producerSemaphore.WaitAsync();

            _logger.Mark(taskName, StateEnum.SemaphoreEnter);

            _logger.Mark(taskName, StateEnum.MutexAttemptAcquire);
            using (await _mutex.AcquireAsync())
            {
                _logger.Mark(taskName, StateEnum.MutexAcquired);
                _buffer.Enqueue(item);
            }

            // wakeup consumers
            _consumerSemaphore.Release();
            _logger.Mark(taskName, StateEnum.SemaphoreReleased);
        }
Example #12
0
        public async Task ExecAsync(int i)
        {
            using (await _gate.AcquireAsync().ConfigureAwait(false))
            {
                Console.Write($"#{i}");
                await Task.Delay(1500).ConfigureAwait(false);

                Console.Write($"{i}# ");
            }
        }
        public async Task AsyncLock_WithGcCollect_Test()
        {
            var  locker = new AsyncLock(TimeSpan.FromMilliseconds(200));
            Task fireForget;

            using (await locker.AcquireAsync())
            {
                CollectGC();
                fireForget = Task.Run(async() =>
                {
                    await Task.Delay(30);
                    using (await locker.AcquireAsync())
                    {
                    }
                });
            }
            CollectGC();
            await fireForget;
        }
Example #14
0
        public async Task Should_throw_oce_if_already_cancelled()
        {
            using var mutex = new AsyncLock();
            using var cts   = new CancellationTokenSource();

            cts.Cancel();

            await Assert.ThrowsAnyAsync <OperationCanceledException>(
                () => mutex.AcquireAsync(cts.Token)
                );
        }
Example #15
0
        public async SystemTasks.Task TestAcquireRelease()
        {
            AsyncLock mutex = AsyncLock.Create();

            Assert.True(!mutex.IsAcquired);
            var releaser = await mutex.AcquireAsync();

            Assert.True(mutex.IsAcquired);
            releaser.Dispose();
            Assert.True(!mutex.IsAcquired);
        }
Example #16
0
        public static async Task AsyncLock_AcquireAsync_Fail()
        {
            using (var l = new AsyncLock())
            {
                using (AsyncLockCookie t1 = await l.AcquireAsync())
                {
                    Assert.True(t1.IsAcquired);
                    using (AsyncLockCookie t2 = await l.AcquireAsync(0))
                    {
                        Assert.False(t2.IsAcquired);
                        Assert.Equal(t2.IsAcquired, t2);
                    }

                    using (AsyncLockCookie t2 = await l.AcquireAsync(TimeSpan.Zero))
                    {
                        Assert.False(t2.IsAcquired);
                        Assert.Equal(t2.IsAcquired, t2);
                    }
                }
            }
        }
Example #17
0
        public static async Task AsyncLock_AcquireAsync_Wait()
        {
            using (var l = new AsyncLock())
            {
                AsyncLockCookie t1 = await l.AcquireAsync();

                Assert.True(t1.IsAcquired);

                var sw = Stopwatch.StartNew();
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    Thread.Sleep(500);
                    t1.Dispose();
                });
                using (AsyncLockCookie t2 = await l.AcquireAsync())
                {
                    Assert.True(t2);
                }
                Assert.True(sw.Elapsed.TotalMilliseconds >= 400);
            }
        }
Example #18
0
 public async Task AsyncLock_Timeout_Test()
 {
     using (var locker = new AsyncLock(TimeSpan.FromMilliseconds(1)))
         using (await locker.AcquireAsync())
         {
             await Task.Run(async() =>
             {
                 try
                 {
                     using (await locker.AcquireAsync(TimeSpan.FromMilliseconds(1)))
                     {
                     }
                     throw new NotSupportedException("Not expected");
                 }
                 catch (TimeoutException)
                 {
                     // expected
                 }
             });
         }
 }
Example #19
0
 public void TestAcquireRelease()
 {
     this.Test(async() =>
     {
         AsyncLock mutex = AsyncLock.Create();
         Specification.Assert(!mutex.IsAcquired, "Mutex is acquired.");
         var releaser = await mutex.AcquireAsync();
         Specification.Assert(mutex.IsAcquired, "Mutex is not acquired.");
         releaser.Dispose();
         Specification.Assert(!mutex.IsAcquired, "Mutex is acquired.");
     });
 }
        public async Task AsyncLock_Test()
        {
            var  locker = new AsyncLock(TimeSpan.FromMilliseconds(200));
            Task fireForget;

            using (await locker.AcquireAsync())
            {
                fireForget = Task.Run(async() =>
                {
                    using (await locker.AcquireAsync())
                    {
                    }
                });
                await Task.Delay(5).ConfigureAwait(false);

                Assert.IsFalse(fireForget.IsCompleted, "fireForget.IsCompleted");
            }
            await Task.Delay(5).ConfigureAwait(false);

            Assert.IsTrue(fireForget.IsCompleted);
            await fireForget;
        }
Example #21
0
        public void TestAcquireTwice()
        {
            if (!this.SystematicTest)
            {
                // .NET cannot detect these deadlocks.
                return;
            }

            this.TestWithError(async() =>
            {
                AsyncLock mutex = AsyncLock.Create();
                await mutex.AcquireAsync();
                await Task.Run(async() =>
                {
                    await mutex.AcquireAsync();
                });
            },
                               expectedError: "Deadlock detected. Task() is waiting for a task to complete, but no other " +
                               "controlled tasks are enabled. Task() is waiting to acquire a resource that is already " +
                               "acquired, but no other controlled tasks are enabled.",
                               replay: true);
        }
Example #22
0
        public override async ValueTask WriteAsync(T item, CancellationToken token)
        {
            using (await writeLock.AcquireAsync(token).ConfigureAwait(false))
            {
                var partition = Partition;
                await writer.SerializeAsync(item, partition, token).ConfigureAwait(false);

                await partition.FlushAsync(token).ConfigureAwait(false);

                cursor.Advance(partition.Position);
            }
            writer.MessageReady();
        }
Example #23
0
        private static async Task CheckAsyncLockReentranceAsync(AsyncLock asyncLock, int maxReentrances = 2)
        {
            using (await asyncLock.AcquireAsync())
            {
                Console.WriteLine($"Lock taken as reentrance: {maxReentrances}.. TaskId: {asyncLock.TaskId}");

                if (maxReentrances > 0)
                {
                    await CheckAsyncLockReentranceAsync(asyncLock, maxReentrances - 1);
                }

                Console.WriteLine($"Press any key to release reentrance: {maxReentrances} lock... TaskId: {asyncLock.TaskId}");
                Console.ReadKey();
            }
        }
Example #24
0
        public static TokenFactory GetAccessTokenFactory(
            [NotNull] this RsdnApiAuthenticator authenticator,
            [NotNull] CodeFlowData flowData,
            [NotNull] IDictionary <string, string> redirectParams)
        {
            Code.NotNull(authenticator, nameof(authenticator));
            Code.NotNull(flowData, nameof(flowData));
            Code.NotNull(redirectParams, nameof(redirectParams));

            AuthTokenResponse token = null;
            var tokenLock           = new AsyncLock();

            return(async ct =>
            {
                if (token == null)
                {
                    using (await tokenLock.AcquireAsync(ct))
                        if (token == null)
                        {
                            token = await authenticator.GetTokenByCodeAsync(flowData, redirectParams, ct);

                            return token.AccessToken;
                        }
                }
                if (token.ExpiresOn >= DateTimeOffset.UtcNow)
                {
                    return token.AccessToken;
                }
                using (await tokenLock.AcquireAsync())
                    if (token.ExpiresOn < DateTimeOffset.UtcNow)
                    {
                        token = await authenticator.RefreshTokenAsync(token.RefreshToken, ct);
                    }
                return token?.AccessToken;
            });
        }
Example #25
0
        private static async Task RegAsyncTestAsync()
        {
            const int RANGE   = 1000;
            var       builder = new ContainerBuilder();
            var       tasks   = Enumerable.Range(0, RANGE)
                                .Select(i => Task.Run(async() =>
            {
                //lock (_sync)
                using (await _lock.AcquireAsync())
                {
                    builder.RegisterType <ConsoleLogger>()
                    .Keyed <ILogger>(i)
                    .SingleInstance();
                    builder.Register <IEnumerable <int> >(c =>
                    {
                        var v = c.Resolve <ILogger>();
                        return(Enumerable.Range(4, 5));
                    });
                }
            }));

            builder.RegisterType <ConsoleLogger>()
            .As <ILogger>()
            .SingleInstance();
            await Task.WhenAll(tasks);

            var container = builder.Build();

            for (int i = 0; i < RANGE; i++)
            {
                if (container.IsRegisteredWithKey <ILogger>(i))
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.Write("V,");
                    Console.ResetColor();
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Magenta;
                    Console.Write("X,");
                    Console.ResetColor();
                }
            }

            Console.WriteLine();
        }
        public async Task <IExchange> DeclareExchangeAsync(string exchangeName, string exchangeType)
        {
            if (exchanges.TryGetValue(exchangeName, out var exchange))
            {
                return(exchange);
            }
            using (await asyncLock.AcquireAsync().ConfigureAwait(false))
            {
                if (exchanges.TryGetValue(exchangeName, out exchange))
                {
                    return(exchange);
                }
                exchange = await advancedBus.ExchangeDeclareAsync(exchangeName, exchangeType).ConfigureAwait(false);

                exchanges[exchangeName] = exchange;
                return(exchange);
            }
        }
Example #27
0
        private async Task InitAsync()
        {
            if (_initialized)
            {
                return;
            }

            using (await _initializeLock.AcquireAsync())
            {
                if (_initialized)
                {
                    return;
                }

                await _easyNetQBus.DeclareMessageBusAsync(_messageBus.Value);

                _initialized = true;
            }
        }
Example #28
0
        public async SystemTasks.Task TestSynchronizeTwoAsynchronousTasks()
        {
            SharedEntry entry = new SharedEntry();
            AsyncLock   mutex = AsyncLock.Create();

            async Task WriteAsync(int value)
            {
                using (await mutex.AcquireAsync())
                {
                    entry.Value = value;
                }
            }

            Task task1 = WriteAsync(3);
            Task task2 = WriteAsync(5);
            await Task.WhenAll(task1, task2);

            Assert.True(task1.IsCompleted && task2.IsCompleted && !mutex.IsAcquired);
            Assert.True(entry.Value == 5, $"Value is '{entry.Value}' instead of 5.");
        }
Example #29
0
        public void TestSynchronizeTwoAsynchronousTasks()
        {
            this.Test(async() =>
            {
                SharedEntry entry = new SharedEntry();
                AsyncLock mutex   = AsyncLock.Create();

                async Task WriteAsync(int value)
                {
                    using (await mutex.AcquireAsync())
                    {
                        entry.Value = value;
                    }
                }

                Task task1 = WriteAsync(3);
                Task task2 = WriteAsync(5);
                await Task.WhenAll(task1, task2);
                AssertSharedEntryValue(entry, 5);
            },
                      configuration: this.GetConfiguration().WithTestingIterations(200));
        }
Example #30
0
        /// <inheritdoc />
        public async Task <T> InvokeChannelActionAsync <T>(
            Func <IModel, T> channelAction, CancellationToken cancellationToken
            )
        {
            Preconditions.CheckNotNull(channelAction, "channelAction");

            using var cts      = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, disposeCts.Token);
            using var releaser = await mutex.AcquireAsync(cts.Token).ConfigureAwait(false);

            var retryTimeoutMs = MinRetryTimeoutMs;

            while (true)
            {
                cts.Token.ThrowIfCancellationRequested();

                try
                {
                    var channel = initializedChannel ??= CreateChannel();
                    return(channelAction(channel));
                }
                catch (Exception exception)
                {
                    var exceptionVerdict = GetExceptionVerdict(exception);
                    if (exceptionVerdict.CloseChannel)
                    {
                        CloseChannel();
                    }

                    if (exceptionVerdict.Rethrow)
                    {
                        throw;
                    }
                }

                await Task.Delay(retryTimeoutMs, cts.Token).ConfigureAwait(false);

                retryTimeoutMs = Math.Min(retryTimeoutMs * 2, MaxRetryTimeoutMs);
            }
        }