public void ItCompletesTheTaskWhenSetIsCalled()
 {
     var asyncARE = new AsyncAutoResetEvent();
     var task = asyncARE.WaitAsync();
     asyncARE.Set();
     task.Wait(TimeSpan.FromSeconds(1));
     Assert.IsTrue(task.IsCompleted);
 }
 public void ItReturnsNewUncompletedTaskAfterExecution()
 {
     var asyncARE = new AsyncAutoResetEvent();
     var task = asyncARE.WaitAsync();
     task.ContinueWith(_ => { });
     asyncARE.Set();
     var newTask = asyncARE.WaitAsync();
     Assert.IsTrue(newTask != task && !newTask.IsCompleted);
 }
Example #3
0
        /// <summary>
        /// Create an instance of a subscription to detect plc data changes
        /// </summary>
        /// <param name="mapper">The reference to the plcDatamapper.</param>
        /// <param name="vars">The variables we should watch.</param>
        /// <param name="defaultInterval">setup the default interval, if none was given by the <see cref="PlcWatchReference"/></param>
        public Subscription(PlcDataMapper mapper, ChangeDetectionStrategy changeDetectionStrategy = ChangeDetectionStrategy.Polling, IEnumerable <PlcWatchReference> vars = null, int defaultInterval = 1000)
        {
            _mapper = mapper ?? ExceptionThrowHelper.ThrowArgumentNullException <PlcDataMapper>(nameof(mapper));
            _changeDetectionStrategy = changeDetectionStrategy;
            _defaultInterval         = defaultInterval;
            _lock = new ReaderWriterLockSlim();
            UpdateWatchCycle(vars);

            if (changeDetectionStrategy == ChangeDetectionStrategy.Event)
            {
                _changeEvent = new AsyncAutoResetEvent <IEnumerable <DataPack> >();
            }
            if (vars != null)
            {
                AddItems(vars);
            }
        }
Example #4
0
    public async Task InvokeWithProgressParameterAsArray()
    {
        AsyncAutoResetEvent signal = new AsyncAutoResetEvent();

        int sum = 0;
        ProgressWithCompletion <int> progress = new ProgressWithCompletion <int>(report =>
        {
            sum += report;
            signal.Set();
        });

        int        n          = 3;
        Task <int> invokeTask = this.clientRpc.InvokeAsync <int>("test", new object[] { n, progress });

        JToken request = await this.ReceiveAsync();

        JToken progressID = request["params"][1];

        // Send responses as $/progress
        int sum2 = 0;

        for (int i = 1; i <= n; i++)
        {
            string  content = "{ \"jsonrpc\": \"2.0\", \"method\": \"$/progress\", \"params\": { \"token\": " + progressID + ", \"value\": " + i + " } }";
            JObject json    = JObject.Parse(content);

            this.Send(json);

            sum2 += i;

            await signal.WaitAsync().WithCancellation(this.TimeoutToken);

            Assert.Equal(sum2, sum);
        }

        this.Send(new
        {
            jsonrpc = "2.0",
            id      = request["id"],
            result  = sum,
        });

        int result = await invokeTask;

        Assert.Equal(sum2, result);
    }
Example #5
0
        public virtual async Task WillExpireRemoteItems()
        {
            using (var firstCache = GetCacheClient() as HybridCacheClient) {
                Assert.NotNull(firstCache);
                var firstResetEvent = new AsyncAutoResetEvent(false);
                Action <object, ItemExpiredEventArgs> expiredHandler = (sender, args) => {
                    _logger.Trace("First local cache expired: {0}", args.Key);
                    firstResetEvent.Set();
                };

                using (firstCache.LocalCache.ItemExpired.AddSyncHandler(expiredHandler)) {
                    using (var secondCache = GetCacheClient() as HybridCacheClient) {
                        Assert.NotNull(secondCache);
                        var secondResetEvent = new AsyncAutoResetEvent(false);
                        Action <object, ItemExpiredEventArgs> expiredHandler2 = (sender, args) => {
                            _logger.Trace("Second local cache expired: {0}", args.Key);
                            secondResetEvent.Set();
                        };

                        using (secondCache.LocalCache.ItemExpired.AddSyncHandler(expiredHandler2)) {
                            string cacheKey = "will-expire-remote";
                            _logger.Trace("First Set");
                            Assert.True(await firstCache.AddAsync(cacheKey, new SimpleModel {
                                Data1 = "test"
                            }, TimeSpan.FromMilliseconds(250)));
                            _logger.Trace("Done First Set");
                            Assert.Equal(1, firstCache.LocalCache.Count);

                            _logger.Trace("Second Get");
                            Assert.True((await secondCache.GetAsync <SimpleModel>(cacheKey)).HasValue);
                            _logger.Trace("Done Second Get");
                            Assert.Equal(1, secondCache.LocalCache.Count);

                            _logger.Trace("Waiting for item expired handlers...");
                            var sw = Stopwatch.StartNew();
                            await firstResetEvent.WaitAsync(TimeSpan.FromSeconds(2));

                            await secondResetEvent.WaitAsync(TimeSpan.FromSeconds(2));

                            sw.Stop();
                            _logger.Trace("Time {0}", sw.Elapsed);
                        }
                    }
                }
            }
        }
        public async Task <bool> StartMoving(string dir)
        {
            AsyncAutoResetEvent doneEvent = new AsyncAutoResetEvent();
            bool success = false;

            SendCommand($":M{dir}#", (a) =>
            {
                MountState.IsSlewing = true;
                ++_moveState;
                success = a.Success;
                doneEvent.Set();
            });

            await doneEvent.WaitAsync();

            return(success);
        }
        public async Task When_subscribe_to_stream_and_append_messages_then_should_receive_message()
        {
            using (var fixture = GetFixture())
            {
                using (var store = await fixture.GetStreamStore())
                {
                    var    streamId1        = "stream-1";
                    var    streamId2        = "stream-2";
                    var    received         = new AsyncAutoResetEvent();
                    string streamIdReceived = null;

                    using (store.SubscribeToStream(
                               streamId1,
                               StreamVersion.None,
                               (_, message, ct) =>
                    {
                        streamIdReceived = message.StreamId;
                        received.Set();
                        return(Task.CompletedTask);
                    }))
                    {
                        await AppendMessages(store, streamId1, 1);
                        await AppendMessages(store, streamId2, 1);

                        await received.WaitAsync().WithTimeout();

                        streamIdReceived.ShouldBe(streamId1);

                        await AppendMessages(store, streamId1, 1);
                        await AppendMessages(store, streamId2, 1);

                        await received.WaitAsync().WithTimeout();

                        streamIdReceived.ShouldBe(streamId1);

                        await AppendMessages(store, streamId1, 1);
                        await AppendMessages(store, streamId2, 1);

                        await received.WaitAsync().WithTimeout();

                        streamIdReceived.ShouldBe(streamId1);
                    }
                }
            }
        }
Example #8
0
 public async Task CompleteGetAsync(string key, QueryResult <KVPair> result)
 {
     if (_getCalls.TryGetValue(key, out var completionSource))
     {
         _getCalls.Remove(key);
         completionSource.SetResult(result);
         await completionSource.Task;
     }
     else
     {
         var serviceCallResetEvent = new AsyncAutoResetEvent(false);
         _waitingGetCalls[key] = serviceCallResetEvent;
         if (!(await serviceCallResetEvent.WaitAsync(500)))
         {
             throw new InvalidOperationException($"Timed out waiting for a request for key '{key}' to be initiated");
         }
     }
 }
Example #9
0
 public async Task CompleteServiceAsync(string serviceName, QueryResult <CatalogService[]> result)
 {
     if (_serviceCalls.TryGetValue(serviceName, out var completionSource))
     {
         _serviceCalls.Remove(serviceName);
         completionSource.SetResult(result);
         await completionSource.Task;
     }
     else
     {
         var serviceCallResetEvent = new AsyncAutoResetEvent(false);
         _waitingServiceCalls[serviceName] = serviceCallResetEvent;
         if (!(await serviceCallResetEvent.WaitAsync(500)))
         {
             throw new InvalidOperationException($"Timed out waiting for a request for service requst '{serviceName}' to be initiated");
         }
     }
 }
Example #10
0
        public async Task <string> SetSiteLatitude(float latitude)
        {
            AsyncAutoResetEvent doneEvent = new AsyncAutoResetEvent();
            bool success = false;
            char sgn     = latitude < 0 ? '-' : '+';
            int  latInt  = (int)Math.Abs(latitude);
            int  latMin  = (int)((Math.Abs(latitude) - latInt) * 60.0f);

            SendCommand($":St{sgn}{latInt:00}*{latMin:00}#,n", (result) =>
            {
                success = result.Success;
                doneEvent.Set();
            });

            await doneEvent.WaitAsync();

            return(success ? "1" : "0");
        }
        public async Task WriteMessage(Stream data, byte[] header = null, int count = 1)
        {
            AsyncAutoResetEvent sendCompleted = new AsyncAutoResetEvent(false);

            using (FixedHeader(header))
            {
                for (int i = 0; i < count; i++)
                {
                    SendMessage(data, () => sendCompleted.Set());
                }
            }

            Assert.True(await sendCompleted.WaitOne(DefaultTimeout),
                        $"Sending client message did not return after {DefaultTimeout}ms.");
//            sendCompleted.WaitOne(DefaultTimeout)
//                         .Should().BeTrue($"client message should have returned after {DefaultTimeout}ms.");
//            return Task.CompletedTask;
        }
Example #12
0
        public DummyGpioPin(
            string name,
            GpioDirection?direction,
            bool?activeLow,
            bool?initialValue,
            TimeSpan?assertionTime,
            TimeSpan?deassertionTime,
            TimeSpan?debounceTime)
        {
            this.Name            = name;
            this.direction       = direction ?? GpioDirection.Input;
            this.value           = initialValue ?? false;
            this.AssertionTime   = assertionTime ?? defaultAssertionTime;
            this.DeassertionTime = deassertionTime ?? defaultDeassertionTime;
            this.DebounceTime    = debounceTime ?? defaultDebounceTime;

            this.pinChangeEvent = new AsyncAutoResetEvent();
            this.isDisposed     = false;
        }
Example #13
0
        public async Task <TOut> Send <TIn, TOut>(string path, TIn data, CancellationToken cancel) where TOut : new()
        {
            using (var strm = new MemoryStream())
            {
                PayloadHelper.WriteData(strm, new PayloadPacketHeader
                {
                    PacketId = GetPacketId(),
                    Path     = path,
                });
                PayloadHelper.WriteData(strm, data);
                var eve = new AsyncAutoResetEvent(false);

                var result  = default(Result <TOut>);
                var dispose = Register <TOut>(path).FirstAsync(_ => true).Subscribe(_ =>
                {
                    result = _;
                    eve.Set();
                });
                try
                {
                    strm.Position = 0;
                    await SendData(PayloadHelper.DefaultNetworkId, PayloadHelper.DefaultSuccessMessageType, strm, cancel);

                    await eve.WaitAsync(cancel);

                    if (result.IsError)
                    {
                        throw new PayloadClientException(path, result.Error);
                    }
                    Debug.Assert(result.Value != null);
                    return(result.Value);
                }
                catch (Exception e)
                {
                    _logger.Error(e, $"Error to get interface implementations:{e.Message}");
                    throw;
                }
                finally
                {
                    dispose.Dispose();
                }
            }
        }
Example #14
0
        public async Task <bool> SetTracking(bool enabled)
        {
            bool success = false;
            AsyncAutoResetEvent doneEvent = new AsyncAutoResetEvent();
            var b = enabled ? 1 : 0;

            SendCommand($":MT{b}#,n", (setResult) =>
            {
                if (setResult.Success)
                {
                    MountState.IsTracking = enabled;
                }
                doneEvent.Set();
            });

            await doneEvent.WaitAsync();

            return(success);
        }
Example #15
0
        public async Task <float> GetSiteLatitude()
        {
            AsyncAutoResetEvent doneEvent = new AsyncAutoResetEvent();
            double latitude = 0;
            bool   success  = false;

            SendCommand(":Gt#,#", (lat) =>
            {
                if (lat.Success && TryParseDec(lat.Data, out latitude))
                {
                    success = true;
                }
                doneEvent.Set();
            });

            await doneEvent.WaitAsync();

            return(success ? (float)latitude : 0);
        }
Example #16
0
        public void SetInlinesContinuationsUnderSwitch()
        {
            this.evt = new AsyncAutoResetEvent(allowInliningAwaiters: true);
            Thread settingThread       = Thread.CurrentThread;
            bool   setReturned         = false;
            var    inlinedContinuation = this.evt.WaitAsync()
                                         .ContinueWith(delegate
            {
                // Arrange to synchronously block the continuation until Set() has returned,
                // which would deadlock if Set does not return until inlined continuations complete.
                Assert.False(setReturned);
                Assert.Same(settingThread, Thread.CurrentThread);
            },
                                                       TaskContinuationOptions.ExecuteSynchronously);

            this.evt.Set();
            setReturned = true;
            Assert.True(inlinedContinuation.IsCompleted);
        }
Example #17
0
        private async Task <IList <TestResult> > ExecuteTests(IEnumerable <TestCase> testCases, CancellationToken token)
        {
            var waitHandle = new AsyncAutoResetEvent();
            var handler    = new RunEventHandler(waitHandle);

            handler.TestResultAvailable += HandlerOnTestResultAvailable;
            var registration = token.Register(vsTestConnector.ConsoleWrapper.CancelTestRun);

            vsTestConnector.ConsoleWrapper.RunTests(testCases, string.Format(MSTestConstants.DefaultRunSettings, Directory.GetCurrentDirectory()), handler);

            await waitHandle.WaitAsync(token);

            handler.TestResultAvailable -= HandlerOnTestResultAvailable;
            registration.Dispose();

            token.ThrowIfCancellationRequested();

            return(handler.TestResults);
        }
Example #18
0
        // Input is -180 (W) to +180 (E)
        // This needs to be mapped to 360..0
        public async Task <string> SetSiteLongitude(float longitude)
        {
            AsyncAutoResetEvent doneEvent = new AsyncAutoResetEvent();
            bool success = false;

            longitude = 180 - longitude;
            int lonInt = (int)longitude;
            int lonMin = (int)((longitude - lonInt) * 60.0f);

            SendCommand($":Sg{lonInt:000}*{lonMin:00}#,n", (result) =>
            {
                success = result.Success;
                doneEvent.Set();
            });

            await doneEvent.WaitAsync();

            return(success ? "1" : "0");
        }
Example #19
0
        public Swarm(
            PrivateKey privateKey,
            TimeSpan dialTimeout,
            IPAddress ipAddress      = null,
            int?listenPort           = null,
            DateTimeOffset?createdAt = null)
        {
            Running = false;

            _privateKey = privateKey
                          ?? throw new ArgumentNullException(nameof(privateKey));
            _dialTimeout       = dialTimeout;
            _peers             = new Dictionary <Peer, DateTimeOffset>();
            _removedPeers      = new Dictionary <Peer, DateTimeOffset>();
            LastSeenTimestamps = new Dictionary <Peer, DateTimeOffset>();

            DateTimeOffset now = createdAt.GetValueOrDefault(
                DateTimeOffset.UtcNow);

            LastDistributed  = now;
            LastReceived     = now;
            DeltaDistributed = new AsyncAutoResetEvent();
            DeltaReceived    = new AsyncAutoResetEvent();
            TxReceived       = new AsyncAutoResetEvent();
            BlockReceived    = new AsyncAutoResetEvent();

            _dealers = new ConcurrentDictionary <Address, DealerSocket>();
            _router  = new RouterSocket();

            _distributeMutex = new AsyncLock();
            _receiveMutex    = new AsyncLock();
            _blockSyncMutex  = new AsyncLock();
            _runningMutex    = new AsyncLock();

            _ipAddress  = ipAddress ?? GetLocalIPAddress();
            _listenPort = listenPort;

            string loggerId = _privateKey.PublicKey.ToAddress().ToHex();

            _logger = Log.ForContext <Swarm>()
                      .ForContext("SwarmId", loggerId);
        }
        public async Task <bool> WaitForCounterAsync(string statName, Func <Task> work, long count = 1, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (count <= 0)
            {
                return(true);
            }

            long     currentCount = count;
            var      resetEvent   = new AsyncAutoResetEvent(false);
            DateTime start        = SystemClock.UtcNow;

            using (Counted.AddHandler((s, e) => {
                currentCount -= e.Value;
                resetEvent.Set();
                return(Task.CompletedTask);
            })) {
                _logger.Trace("Wait: count={count}", currentCount);

                if (work != null)
                {
                    await work().AnyContext();
                }

                if (currentCount <= 0)
                {
                    return(true);
                }

                do
                {
                    try {
                        await resetEvent.WaitAsync(cancellationToken).AnyContext();
                    } catch (OperationCanceledException) { }

                    _logger.Trace("Got signal: count={currentCount} expected={count}", currentCount, count);
                } while (cancellationToken.IsCancellationRequested == false && currentCount > 0);
            }

            _logger.Trace("Done waiting: count={currentCount} expected={count} success={success} time={time}", currentCount, count, currentCount <= 0, SystemClock.UtcNow.Subtract(start));

            return(currentCount <= 0);
        }
Example #21
0
        public async Task StartAsync_processes_handle_proxy_delegates(int concurrency, int delegatesNumber)
        {
            var channel = Channel.CreateUnbounded <HandleProxy>();

            var configuration = new BackgroundHandleProxyProcessorConfiguration(concurrency);

            var logger = Mock.Of <ILogger <BackgroundHandleProxyProcessor> >();

            var processor = new BackgroundHandleProxyProcessor(channel.Reader, configuration, logger);

            _ = processor.StartAsync(CancellationToken.None);

            AsyncAutoResetEvent resetEvent = new AsyncAutoResetEvent(false);

            Task WriteAsyncDelegate(int index) => channel.Writer.WriteAsync(cancellationToken =>
            {
                logger.LogInformation($"item: {index}");

                if (index == delegatesNumber - 1)
                {
                    resetEvent.Set();
                }

                return(Task.CompletedTask);
            }).AsTask();

            Task[] writeTasks = Enumerable.Range(0, delegatesNumber).Select(WriteAsyncDelegate).ToArray();

            await Task.WhenAll(writeTasks);

            await resetEvent.WaitAsync();

            Mock.Get(logger)
            .Verify(
                l => l.Log(
                    It.Is <LogLevel>(l => l == LogLevel.Information),
                    It.IsAny <EventId>(),
                    It.IsAny <It.IsAnyType>(),
                    It.Is <Exception>(e => e == null),
                    It.IsAny <Func <It.IsAnyType, Exception, string> >()),
                Times.Exactly(delegatesNumber));
        }
Example #22
0
        public async Task WaitCancel()
        {
            var Event = new AsyncAutoResetEvent();

            using var TokenSource = new CancellationTokenSource();

            var Task = Event.Wait(TokenSource.Token);

            TokenSource.Cancel();

            try
            {
                await Task;

                Assert.Fail("Did not cancel");
            }
            catch (OperationCanceledException)
            {
            }
        }
Example #23
0
        public async Task <bool> StopMoving(string dir)
        {
            AsyncAutoResetEvent doneEvent = new AsyncAutoResetEvent();
            bool success = false;

            SendCommand($":Q{dir}#", (a) =>
            {
                --_moveState;
                if (_moveState <= 0)
                {
                    _moveState           = 0;
                    MountState.IsSlewing = false;
                }
                success = a.Success;
                doneEvent.Set();
            });
            await doneEvent.WaitAsync();

            return(success);
        }
Example #24
0
        public static async Task <bool> WaitAsync(this AsyncAutoResetEvent mEvent, TimeSpan timeout, CancellationToken token = default)
        {
            var timeOut = new CancellationTokenSource(timeout);
            var comp    = CancellationTokenSource.CreateLinkedTokenSource(timeOut.Token, token);

            try
            {
                await mEvent.WaitAsync(comp.Token).ConfigureAwait(false);

                return(true);
            }
            catch (OperationCanceledException e)
            {
                if (token.IsCancellationRequested)
                {
                    throw;     //Forward OperationCanceledException from external Token
                }
                return(false); //Here the OperationCanceledException was raised by Timeout
            }
        }
Example #25
0
        public OrchestrationSession(
            string storageAccountName,
            string taskHubName,
            OrchestrationInstance orchestrationInstance,
            IReadOnlyList <MessageData> initialMessageBatch,
            OrchestrationRuntimeState runtimeState,
            string eTag,
            TimeSpan idleTimeout,
            Guid traceActivityId)
            : base(storageAccountName, taskHubName, orchestrationInstance, traceActivityId)
        {
            this.idleTimeout         = idleTimeout;
            this.CurrentMessageBatch = initialMessageBatch ?? throw new ArgumentNullException(nameof(initialMessageBatch));
            this.RuntimeState        = runtimeState ?? throw new ArgumentNullException(nameof(runtimeState));
            this.ETag = eTag;

            this.messagesAvailableEvent = new AsyncAutoResetEvent(signaled: false);
            this.sessionReleasedEvent   = new AsyncManualResetEvent();
            this.nextMessageBatch       = new MessageCollection();
        }
Example #26
0
        public async Task <bool> SendCommandAsync(Command command)
        {
            if (command.Source != CommandSource.Client)
            {
                throw new ArgumentException("Command source is invalid.", nameof(command));
            }

            bool result = false;
            var  ev     = new AsyncAutoResetEvent();

            _Connection.SendAsync(command.Serialize(), (r) => {
                result = r;
                ev.Set();
            });
            OnSendMessage?.Invoke(this, new CommandEventArgs(command));

            await ev.WaitAsync();

            return(result);
        }
 public InvocationItem(
     Action action,
     IServiceActorWrapper target,
     string typeOfObjectToWrap,
     bool keepContextForAsyncCalls = true,
     bool async = false)
 {
     Action                   = action;
     Target                   = target;
     TypeOfObjectToWrap       = typeOfObjectToWrap;
     KeepContextForAsyncCalls = keepContextForAsyncCalls;
     if (async)
     {
         _asyncAutoResetEvent = new AsyncAutoResetEvent(false);
     }
     else
     {
         _autoResetEvent = new AutoResetEvent(false);
     }
 }
        internal InMemoryMessagePublisherReceiver(int maxBatchSize = 50, ILogger logger = null)
        {
            if (maxBatchSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxBatchSize), maxBatchSize,
                                                      "The maximum batch size has to be positive number.");
            }

            _logger = logger ?? NullLogger.Instance;
            _shutdownTokenSource = new CancellationTokenSource();

            _processingTriggerEvent = new AsyncAutoResetEvent(false);
            _notProcessingEvent     = new AsyncManualResetEvent(true);

            _queue           = new ConcurrentQueue <Message>();
            _deadLetterQueue = new Collection <Message>();
            _consumers       = new ConcurrentDictionary <Func <IReadOnlyCollection <Message>, CancellationToken, Task>, CancellationToken>();

            _backgroundTask = StartBackgroundTaskAsync(maxBatchSize);
        }
Example #29
0
        public async Task DelayedCancelWithTimeout()
        {
            var a = new AsyncAutoResetEvent();

            using var cts = new CancellationTokenSource(1000);

            var sw = Stopwatch.StartNew();

            try
            {
                await a.WaitAsync(10_000, cts.Token);
            }
            catch (OperationCanceledException)
            {
                sw.Stop();
                Assert.InRange(sw.ElapsedMilliseconds, 1000, 10_000);
                return;
            }
            Assert.True(false);
        }
Example #30
0
        private async void OnTimer(object s, EventArgs e)
        {
            _timerStatus.Stop();
            if (_mountVM.ConnectionState.StartsWith("Connected"))
            {
                bool restartTimer = true;
                var  gxDoneEvent  = new AsyncAutoResetEvent();
                _sendCommand(":GX#,#", (result) =>
                {
                    if (result.Success)
                    {
                        var parts = result.Data.Split(',');
                        if (!_currentStatusFunc(parts))
                        {
                            restartTimer = false;
                            WpfUtilities.RunOnUiThread(() => { this.DialogResult = true; this.Close(); }, Application.Current.Dispatcher);
                        }
                    }
                    else
                    {
                        if (!_currentStatusFunc(null))
                        {
                            restartTimer = false;
                            WpfUtilities.RunOnUiThread(() => { this.DialogResult = true; this.Close(); }, Application.Current.Dispatcher);
                        }
                    }
                    gxDoneEvent.Set();
                });

                await gxDoneEvent.WaitAsync();

                if (restartTimer)
                {
                    _timerStatus.Start();
                }
            }
            else
            {
                WpfUtilities.RunOnUiThread(() => { this.DialogResult = true; this.Close(); }, Application.Current.Dispatcher);
            }
        }
Example #31
0
        public static async Task <bool> WaitOneWithAliveEvent(this AsyncAutoResetEvent waitHandle, int timeout,
                                                              AsyncAutoResetEvent aliveEvent)
        {
            if (await waitHandle.WaitOne(timeout))
            {
                return(true);
            }
            while (await aliveEvent.WaitOne(timeout))
            {
                if (await waitHandle.WaitOne(0))
                {
                    return(true);
                }
            }
            if (await waitHandle.WaitOne(timeout))
            {
                return(true);
            }

            return(false);
        }
        /// <summary>
        /// Initializes the processing pipeline stage (base class specific part).
        /// </summary>
        internal override void OnInitializeBase()
        {
            try
            {
                // set up asynchronous processing
                mAsyncProcessingMessageStack            = new LocklessStack <LocalLogMessage>(mMessageQueueSize, false);
                mTriggerAsyncProcessingEvent            = new AsyncAutoResetEvent(false);
                mAsyncProcessingCancellationTokenSource = new CancellationTokenSource();
                mTerminateProcessingTask = false;
                mAsyncContextThread      = new AsyncContextThread();
                mAsyncProcessingTask     = mAsyncContextThread.Factory.Run(ProcessingTask);

                // Perform pipeline stage specific initialization
                OnInitialize();
            }
            catch (Exception)
            {
                Shutdown();
                throw;
            }
        }
 public void ItReturnsTaskWhenWaitAsyncIsCalled()
 {
     var asyncARE = new AsyncAutoResetEvent();
     Assert.IsInstanceOfType(asyncARE.WaitAsync(), typeof(Task));
 }
		public async Task concurrentWaits()
		{
			var token = new CancellationToken();
			var ev = new AsyncAutoResetEvent();
			ev.Set();

			ThreadPool.UnsafeQueueUserWorkItem(async (s) =>
			{
				for (int i = 0; i < 100; i++)
				{
					Thread.Sleep(2);
					var t = ev.WaitAsync(token);
					if (t == Task.CompletedTask)
						Console.WriteLine("[1] Took it " + i);
					else
						await t.ContinueWith((t1, s1) =>
						{
							Console.WriteLine("[1] Took it later " + i);
						}, null);
				}
				Console.WriteLine("[1] done ");
			}, null);

			ThreadPool.UnsafeQueueUserWorkItem(async (s) =>
			{
				for (int i = 0; i < 100; i++)
				{
					Thread.Sleep(2);
					var t = ev.WaitAsync(token);
					if (t == Task.CompletedTask)
						Console.WriteLine("[2] Took it " + i);
					else
						await t.ContinueWith((t1, s1) =>
						{
							Console.WriteLine("[2] Took it later " + i);
						}, null);
				}
				Console.WriteLine("[2] done ");
			}, null);

			ThreadPool.UnsafeQueueUserWorkItem(async (s) =>
			{
				for (int i = 0; i < 100; i++)
				{
					Thread.Sleep(2);
					var t = ev.WaitAsync(token);
					if (t == Task.CompletedTask)
						Console.WriteLine("[3] Took it " + i);
					else
						await t.ContinueWith((t1, s1) =>
						{
							Console.WriteLine("[3] Took it later " + i);
						}, null);
				}
				Console.WriteLine("[3] done ");
			}, null);

			ThreadPool.UnsafeQueueUserWorkItem((s) =>
			{
				for (int i = 0; i < 400; i++)
				{
					Thread.Sleep(1);
					ev.Set();
				}
			}, null);

			Thread.CurrentThread.Join(TimeSpan.FromSeconds(15));
		}