Ejemplo n.º 1
0
        protected override async Task <string> EnqueueImplAsync(T data)
        {
            string id = Guid.NewGuid().ToString("N");

            _logger.Trace("Queue {0} enqueue item: {1}", _options.Name, id);

            if (!await OnEnqueuingAsync(data).AnyContext())
            {
                return(null);
            }

            var entry = new QueueEntry <T>(id, data.DeepClone(), this, SystemClock.UtcNow, 0);

            _queue.Enqueue(entry);
            _logger.Trace("Enqueue: Set Event");

            _autoResetEvent.Set();
            Interlocked.Increment(ref _enqueuedCount);

            await OnEnqueuedAsync(entry).AnyContext();

            _logger.Trace("Enqueue done");

            return(id);
        }
        public void WhenEventIsBecameSignaled_WaitedClientsShouldStopWaitedwithFIFO()
        {
            var sut = new AsyncAutoResetEvent();

            var task1 = Task.Run(() => sut.Wait());

            Thread.Sleep(300);
            var task2 = Task.Run(() => sut.Wait());

            Thread.Sleep(300);
            var task3 = Task.Run(() => sut.Wait());

            Thread.Sleep(300);

            var task = Task.WhenAny(task1, task2, task3);

            sut.Set();
            var finishedTask = task.Result;

            Assert.AreEqual(finishedTask, task1);

            task = Task.WhenAny(task2, task3);
            sut.Set();
            finishedTask = task.Result;
            Assert.AreEqual(finishedTask, task2);
        }
Ejemplo n.º 3
0
        public void SetAuthenticationStateTask(Task <AuthenticationState> task)
        {
            if (_isHoldingFakeAuthTask)
            {
                _forFakeStateTaskRealTask = task;
                _isHoldingFakeAuthTask    = false;

                if (!_initialStateReady.IsSet)
                {
                    _initialStateReady.Set();
                }

                //NotifyAuthenticationStateChanged(_authenticationStateTask);
            }
            else
            {
                _authenticationStateTask = task;

                if (!_initialStateReady.IsSet)
                {
                    _initialStateReady.Set();
                }

                NotifyAuthenticationStateChanged(_authenticationStateTask);
            }
        }
Ejemplo n.º 4
0
        // Authorization code flow using OIDAuthState automatic code exchanges.
        public async Task <AuthInfo> LoginAsync()
        {
            //var issuer = new NSUrl(Constants.Issuer);
            var redirectUri = new NSUrl(Constants.RedirectUri);

            //Console.WriteLine($"Fetching configuration for issuer: {issuer}");

            try
            {
                // discovers endpoints
                var configuration =
                    await AuthorizationService.DiscoverServiceConfigurationForDiscoveryAsync(
                        new NSUrl(Constants.DiscoveryEndpoint));

                Console.WriteLine($"Got configuration: {configuration}");

                // builds authentication request
                var request = new AuthorizationRequest(configuration, Constants.ClientId,
                                                       new string[] { Scope.OpenId, Scope.Profile, "offline_access" }, redirectUri, ResponseType.Code, null);
                // performs authentication request
                var appDelegate = (AppDelegate)UIApplication.SharedApplication.Delegate;
                Console.WriteLine($"Initiating authorization request with scope: {request.Scope}");

                appDelegate.CurrentAuthorizationFlow = AuthState.PresentAuthorizationRequest(request,
                                                                                             UIKit.UIApplication.SharedApplication.KeyWindow.RootViewController, (authState, error) =>
                {
                    if (authState != null)
                    {
                        _authState = authState;
                        Console.WriteLine(
                            $"Got authorization tokens. Access token: {authState.LastTokenResponse.AccessToken}");
                    }
                    else
                    {
                        Console.WriteLine($"Authorization error: {error.LocalizedDescription}");
                        _authState = null;
                    }
                    //We need this line to tell the Login method to return the result
                    _loginResultWaitHandle.Set();
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error retrieving discovery document: {ex}");
                _authState = null;
                //We need this line to tell the Login method to return the result
                _loginResultWaitHandle.Set();
            }

            await _loginResultWaitHandle.WaitAsync();

            return(new AuthInfo()
            {
                IsAuthorized = _authState?.IsAuthorized ?? false,
                AccessToken = _authState?.LastTokenResponse?.AccessToken,
                IdToken = _authState?.LastTokenResponse?.IdToken,
                RefreshToken = _authState?.LastTokenResponse?.RefreshToken,
                Scope = _authState?.LastTokenResponse?.Scope
            });
        }
Ejemplo n.º 5
0
        public async Task AsyncAutoResetEvent()
        {
            var aare = new AsyncAutoResetEvent();

            var globalI = 0;

#pragma warning disable 4014
            Task.Run(async() =>
#pragma warning restore 4014
            {
                await aare.WaitOneAsync(CancellationToken.None);
                globalI += 1;
            });

#pragma warning disable 4014
            Task.Run(async() =>
#pragma warning restore 4014
            {
                await aare.WaitOneAsync(CancellationToken.None);
                globalI += 2;
            });

            await Task.Delay(500);

            aare.Set();
            await Task.Delay(500);

            aare.Set();
            await Task.Delay(100);

            Assert.AreEqual(3, globalI);
        }
Ejemplo n.º 6
0
        private async Task Poll()
        {
            var headPosition         = AllStreamPosition.None;
            var previousHeadPosition = headPosition;

            while (!_disposed.IsCancellationRequested)
            {
                try
                {
                    headPosition = await _getHeadPosition(_disposed.Token).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    await Extensions.HandleException(() => _onError(ex, headPosition)).ConfigureAwait(false);
                }

                if (headPosition > previousHeadPosition)
                {
                    _autoResetEvent.Set();
                    previousHeadPosition = headPosition;
                }
                else
                {
                    await Task.Delay(_interval, _disposed.Token);
                }
            }
        }
Ejemplo n.º 7
0
        internal void NotifyOfCallback(Intent intent)
        {
            try
            {
                if (!intent.HasExtra(Constants.AuthStateKey))
                {
                    _authState = null;
                }
                else
                {
                    try
                    {
                        _authState = AuthState.JsonDeserialize(intent.GetStringExtra(Constants.AuthStateKey));
                    }
                    catch (JSONException ex)
                    {
                        Console.WriteLine("Malformed AuthState JSON saved: " + ex);
                        _authState = null;
                    }
                }
                if (_authState != null)
                {
                    AuthorizationResponse  response = AuthorizationResponse.FromIntent(intent);
                    AuthorizationException authEx   = AuthorizationException.FromIntent(intent);
                    _authState.Update(response, authEx);

                    if (response != null)
                    {
                        Console.WriteLine("Received AuthorizationResponse.");
                        try
                        {
                            var clientAuthentication = _authState.ClientAuthentication;
                        }
                        catch (ClientAuthenticationUnsupportedAuthenticationMethod ex)
                        {
                            _loginResultWaitHandle.Set();

                            Console.WriteLine(
                                "Token request cannot be made, client authentication for the token endpoint could not be constructed: " +
                                ex);

                            return;
                        }
                        _authService.PerformTokenRequest(response.CreateTokenExchangeRequest(), ReceivedTokenResponse);
                    }
                    else
                    {
                        Console.WriteLine("Authorization failed: " + authEx);
                    }
                }
                else
                {
                    _loginResultWaitHandle.Set();
                }
            }
            catch (Exception)
            {
                _loginResultWaitHandle.Set();
            }
        }
        public static async Task <SocketError> ExecuteAsync(this Socket socket,
                                                            Func <Socket, Func <SocketAsyncEventArgs, bool> > methodPredicate,
                                                            SocketAsyncEventArgs socketAsyncEventArgs,
                                                            CancellationToken cancellationToken)
        {
            var asyncAutoResetEvent = new AsyncAutoResetEvent(false);

            socketAsyncEventArgs.Completed += (sender,
                                               args) =>
            {
                asyncAutoResetEvent.Set();
            };

            var method = methodPredicate.Invoke(socket);
            var async  = method.Invoke(socketAsyncEventArgs);

            if (!async)
            {
                asyncAutoResetEvent.Set();
            }

            await asyncAutoResetEvent.WaitAsync(cancellationToken);

            return(socketAsyncEventArgs.SocketError);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// <para>Events:</para>
        /// <para>@emits routerclose</para>
        /// <para>@emits @close</para>
        /// <para>@emits @newproducer - (producer: Producer)</para>
        /// <para>@emits @producerclose - (producer: Producer)</para>
        /// <para>@emits @newdataproducer - (dataProducer: DataProducer)</para>
        /// <para>@emits @dataproducerclose - (dataProducer: DataProducer)</para>
        /// <para>Observer events:</para>
        /// <para>@emits close</para>
        /// <para>@emits newproducer - (producer: Producer)</para>
        /// <para>@emits newconsumer - (producer: Producer)</para>
        /// <para>@emits newdataproducer - (dataProducer: DataProducer)</para>
        /// <para>@emits newdataconsumer - (dataProducer: DataProducer)</para>
        /// </summary>
        /// <param name="loggerFactory"></param>
        /// <param name="transportInternalData"></param>
        /// <param name="sctpParameters"></param>
        /// <param name="sctpState"></param>
        /// <param name="channel"></param>
        /// <param name="payloadChannel"></param>
        /// <param name="appData"></param>
        /// <param name="getRouterRtpCapabilities"></param>
        /// <param name="getProducerById"></param>
        /// <param name="getDataProducerById"></param>
        protected Transport(ILoggerFactory loggerFactory,
                            TransportInternalData transportInternalData,
                            SctpParameters?sctpParameters,
                            SctpState?sctpState,
                            Channel channel,
                            PayloadChannel payloadChannel,
                            Dictionary <string, object>?appData,
                            Func <RtpCapabilities> getRouterRtpCapabilities,
                            Func <string, Producer?> getProducerById,
                            Func <string, DataProducer?> getDataProducerById
                            )
        {
            _loggerFactory = loggerFactory;
            _logger        = loggerFactory.CreateLogger <Transport>();

            // Internal
            Internal = transportInternalData;

            // Data
            SctpParameters = sctpParameters;
            SctpState      = sctpState;

            Channel                  = channel;
            PayloadChannel           = payloadChannel;
            AppData                  = appData;
            GetRouterRtpCapabilities = getRouterRtpCapabilities;
            GetProducerById          = getProducerById;
            GetDataProducerById      = getDataProducerById;

            ProducersLock.Set();
            ConsumersLock.Set();
            DataProducersLock.Set();
            DataConsumersLock.Set();
            CloseLock.Set();
        }
        public async Task When_all_stream_subscription_disposed_while_handling_messages_then_should_drop_subscription_with_reason_Disposed()
        {
            using (var fixture = GetFixture())
            {
                using (var store = await fixture.GetStreamStore())
                {
                    string streamId     = "stream-1";
                    var    droppedTcs   = new TaskCompletionSource <SubscriptionDroppedReason>();
                    var    handler      = new AsyncAutoResetEvent();
                    var    subscription = store.SubscribeToAll(
                        Position.End,
                        async(_, __) =>
                    {
                        handler.Set();
                        await handler.WaitAsync().WithTimeout();     // block "handling" while a dispose occurs
                    },
                        (_, reason, __) =>
                    {
                        droppedTcs.SetResult(reason);
                    });
                    // First message is blocked in handling, the second is co-operatively cancelled
                    await subscription.Started;
                    await AppendMessages(store, streamId, 2);

                    await handler.WaitAsync().WithTimeout(5000);

                    subscription.Dispose();
                    handler.Set();

                    var droppedReason = await droppedTcs.Task.WithTimeout();

                    droppedReason.ShouldBe(SubscriptionDroppedReason.Disposed);
                }
            }
        }
Ejemplo n.º 11
0
        protected override async Task <string> EnqueueImplAsync(T data, QueueEntryOptions options)
        {
            string id = Guid.NewGuid().ToString("N");

            _logger.LogTrace("Queue {Name} enqueue item: {Id}", _options.Name, id);

            if (!await OnEnqueuingAsync(data, options).AnyContext())
            {
                return(null);
            }

            var entry = new QueueEntry <T>(id, options?.CorrelationId, data.DeepClone(), this, SystemClock.UtcNow, 0);

            entry.Properties.AddRange(options?.Properties);

            _queue.Enqueue(entry);
            _logger.LogTrace("Enqueue: Set Event");

            _autoResetEvent.Set();
            Interlocked.Increment(ref _enqueuedCount);

            await OnEnqueuedAsync(entry).AnyContext();

            _logger.LogTrace("Enqueue done");

            return(id);
        }
Ejemplo n.º 12
0
        protected override async Task <string> EnqueueImplAsync(T data, QueueEntryOptions options)
        {
            string id = Guid.NewGuid().ToString("N");

            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("Queue {Name} enqueue item: {EntryId}", _options.Name, id);
            }

            bool isTraceLogLevelEnabled = _logger.IsEnabled(LogLevel.Trace);

            if (!await OnEnqueuingAsync(data, options).AnyContext())
            {
                if (isTraceLogLevelEnabled)
                {
                    _logger.LogTrace("Aborting enqueue item: {EntryId}", id);
                }
                return(null);
            }

            var now      = SystemClock.UtcNow;
            var envelope = new RedisPayloadEnvelope <T> {
                Properties    = options.Properties,
                CorrelationId = options.CorrelationId,
                Value         = data
            };
            bool success = await Run.WithRetriesAsync(() => _cache.AddAsync(GetPayloadKey(id), envelope, _payloadTimeToLive), logger : _logger).AnyContext();

            if (!success)
            {
                throw new InvalidOperationException("Attempt to set payload failed.");
            }

            await Run.WithRetriesAsync(() => Task.WhenAll(
                                           _cache.SetAsync(GetEnqueuedTimeKey(id), now.Ticks, _payloadTimeToLive),
                                           Database.ListLeftPushAsync(_queueListName, id)
                                           ), logger : _logger).AnyContext();

            try {
                _autoResetEvent.Set();
                await Run.WithRetriesAsync(() => _subscriber.PublishAsync(GetTopicName(), id), logger : _logger).AnyContext();
            } catch (Exception ex) {
                if (isTraceLogLevelEnabled)
                {
                    _logger.LogTrace(ex, "Error publishing topic message");
                }
            }

            Interlocked.Increment(ref _enqueuedCount);
            var entry = new QueueEntry <T>(id, null, data, this, now, 0);

            await OnEnqueuedAsync(entry).AnyContext();

            if (isTraceLogLevelEnabled)
            {
                _logger.LogTrace("Enqueue done");
            }
            return(id);
        }
Ejemplo n.º 13
0
 private void AddMessage(Message message)
 {
     lock (_messages)
     {
         _messages.Add(message);
     }
     _updateAvailableEvent.Set();
 }
Ejemplo n.º 14
0
 public void OnCompleted()
 {
     lock (queue)
     {
         completed = true;
     }
     next.Set();
 }
Ejemplo n.º 15
0
    async Task MainLoopAsync(CancellationToken cancel)
    {
        try
        {
            while (true)
            {
                if (cancel.IsCancellationRequested)
                {
                    return;
                }

                while (true)
                {
                    if (this.SendQueue.TryDequeue(out Datagram? dg) == false)
                    {
                        break;
                    }

                    try
                    {
                        IPAddress ip = await this.TcpIp.GetIpAsync(this.Options.SyslogServerHostname, cancel: cancel, orderBy : ip => (long)ip.AddressFamily *(this.Options.PreferIPv6 ? -1 : 1));

                        DatagramSock?sock = null;

                        if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                        {
                            sock = this.UdpSock_IPv4;
                        }
                        else if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                        {
                            sock = this.UdpSock_IPv6;
                        }
                        if (sock != null)
                        {
                            await sock.SendDatagramAsync(new Datagram(dg.Data, new IPEndPoint(ip, this.Options.SyslogServerPort)), cancel, this.Options.SendTimeoutMsecs, true);
                        }
                    }
                    catch
                    {
                        await cancel._WaitUntilCanceledAsync(256); // 念のため
                    }
                }

                if (cancel.IsCancellationRequested)
                {
                    return;
                }

                EmptyEvent.Set(true);

                await TaskUtil.WaitObjectsAsync(cancels : cancel._SingleList(), events : this.NewDataArrivedEvent._SingleList());
            }
        }
        finally
        {
            EmptyEvent.Set(true);
        }
    }
Ejemplo n.º 16
0
        public ProcessFacade(string fileName, string arguments, string workingDirectory,
                             ExecutionContext executionContext, string displayName,
                             bool showOutput, bool showError, bool killOnDispose, OSPlatform platform,
                             CancellationToken cancellationToken)
        {
            this.executionContext = executionContext;
            this.showOutput       = showOutput;
            this.showError        = showError;
            this.killOnDispose    = killOnDispose;
            this.platform         = platform;
            this.displayName      = displayName;
            ProcessStartInfo processInfo = new ProcessStartInfo(fileName, arguments)
            {
                CreateNoWindow         = true,
                UseShellExecute        = false,
                RedirectStandardInput  = true,
                RedirectStandardOutput = true,
                RedirectStandardError  = true
            };

            if (!string.IsNullOrEmpty(workingDirectory))
            {
                processInfo.WorkingDirectory = workingDirectory;
            }

            executionContext.WriteVerbose($"Starting process {processInfo.FileName} {processInfo.Arguments} in {processInfo.WorkingDirectory}.");
            internalProcess = System.Diagnostics.Process.Start(processInfo);
            if (internalProcess != null && !internalProcess.HasExited)
            {
                try
                {
                    processName = internalProcess.ProcessName;
                    internalProcess.OutputDataReceived += InternalProcessOnOutputDataReceived;
                    internalProcess.ErrorDataReceived  += InternalProcessOnErrorDataReceived;
                    internalProcess.EnableRaisingEvents = true;
                    internalProcess.Exited += InternalProcessOnExited;
                    internalProcess.BeginOutputReadLine();
                    outputReadStarted = true;
                    internalProcess.BeginErrorReadLine();
                    errorReadStarted = true;
                }
                catch (Exception e)
                {
                    processName = "unknown process";
                    executionContext.WriteWarning($"Error while starting process: {e}", false);
                    //this happens when the process exits somewhere in this if clause
                }

                cancellationToken.Register(Dispose);
            }
            else
            {
                processName = "unknown process";
                exitedResetEvent.Set();
            }
        }
Ejemplo n.º 17
0
        private async Task ReadBlocksAsync()
        {
            var cancellationToken = CancellationTokenSource.Token;

            try
            {
                while (!EndOfStream && !cancellationToken.IsCancellationRequested)
                {
                    var message = Context.Request.Clone();
                    message.Id = 0;

                    // Strip out any block options
                    message.Options.RemoveAll(o => o is Block1 || o is Block2);

                    message.Options.Add(new Block2(_readBlockNumber, BlockSizeInternal));

                    Context.MessageId = await Context.Client.SendAsync(message, Endpoint, cancellationToken);

                    var response = await Context.Client.GetResponseAsync(Context.MessageId, cancellationToken);

                    if (!response.Code.IsSuccess())
                    {
                        throw new CoapBlockException("Error occured while reading blocks from remote endpoint",
                                                     CoapException.FromCoapMessage(response), response.Code);
                    }

                    var block2 = response.Options.Get <Block2>();

                    if (block2.BlockNumber != _readBlockNumber)
                    {
                        throw new CoapBlockException("Received incorrect block number from remote host");
                    }

                    _readBlockNumber++;

                    _reader.Enqueue(response.Payload, 0, response.Payload.Length);
                    _readerEvent.Set();

                    if (!response.Options.Get <Block2>().IsMoreFollowing)
                    {
                        EndOfStream      = true;
                        Context.Response = response;
                    }
                }
            }
            catch (Exception ex)
            {
                // Hold onto the exception to throw it from a synchronous call.
                CaughtException = ex;
            }
            finally
            {
                EndOfStream = true;
                _readerEvent.Set();
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Attempt to flush any blocks to <see cref="CoapClient"/> that have been queued up.
        /// </summary>
        /// <inheritdoc/>
        public override void Flush()
        {
            if (CaughtException == null && !_writerTask.IsCompleted)
            {
                _writerEvent.Set();
                FlushFinishedEvent.WaitAsync(CancellationToken.None).Wait();
            }

            ThrowExceptionIfCaught();
        }
Ejemplo n.º 19
0
 public Task InvokeReceiveAsync(ArraySegment <byte> buffer, WebSocketMessageType messageType, bool endOfMessage)
 {
     receiveBuffers.Enqueue(new MessageData()
     {
         Buffer       = buffer,
         MessageType  = messageType,
         EndOfMessage = endOfMessage,
     });
     receiveEvent.Set();
     return(Task.CompletedTask);
 }
Ejemplo n.º 20
0
        // Only call at the end of the Mainloop or HeartbeatLoop
        public async Task FinishClose()
        {
            // Notify hearbeat loops that they can leave
            m_heartbeatRead.Set();
            m_closed = true;
            MaybeStopHeartbeatTimers();

            m_frameHandler.Close();
            m_model0.SetCloseReason(m_closeReason);
            await m_model0.FinishClose();
        }
Ejemplo n.º 21
0
        private Task UponorClientOnOnSuccessfulResponse()
        {
            ISensorContainer sensor = _hassMqttManager.GetSensor(DeviceId, EntityId);

            sensor.SetValue(HassTopicKind.State, OkMessage);
            sensor.SetAttribute("last_ok", DateTime.UtcNow.ToString("O"));

            _shouldFlush.Set();

            return(Task.CompletedTask);
        }
Ejemplo n.º 22
0
        public async Task MultipleWaitAsync_AfterMultipleSet_OnlyOneIsCompleted()
        {
            var are = new AsyncAutoResetEvent();

            are.Set();
            are.Set();
            var task1 = are.WaitAsync();
            var task2 = are.WaitAsync();

            Assert.True(task1.IsCompleted);
            await AsyncAssert.NeverCompletesAsync(task2);
        }
        /// <inheritdoc/>
        public Task PublishAsync(IEnumerable <Message> messages, CancellationToken cancellationToken = default)
        {
            return(Task.Run(() =>
            {
                foreach (var message in messages)
                {
                    _queue.Enqueue(message);
                }

                _processingTriggerEvent.Set();
            }, cancellationToken));
        }
Ejemplo n.º 24
0
        public async Task MultipleWaitAsync_AfterMultipleSet_OnlyOneIsCompleted()
        {
            AsyncAutoResetEvent are = new AsyncAutoResetEvent();

            are.Set();
            are.Set();
            Task task1 = are.WaitAsync();
            Task task2 = are.WaitAsync();

            Assert.True(task1.IsCompleted);
            await AsyncAssert.NeverCompletesAsync(task2).ConfigureAwait(false);
        }
Ejemplo n.º 25
0
        public void StopWorking()
        {
            Log.Trace().Message("Queue {0} stop working", _queueName).Write();
            _workerAction = null;
            _subscriber.UnsubscribeAll();

            if (_workerCancellationTokenSource != null)
            {
                _workerCancellationTokenSource.Cancel();
            }

            _autoEvent.Set();
        }
Ejemplo n.º 26
0
 public async Task SingleThreadedPulse()
 {
     for (int i = 0; i < 5; i++)
     {
         var t = _aare.WaitOneAsync();
         Assert.IsFalse(t.IsCompleted);
         _aare.Set();
         await t;
         Assert.IsTrue(t.IsCompleted);
     }
 }
        public void MultipleWaitAsync_AfterMultipleSet_OnlyOneIsCompleted()
        {
            AsyncContext.Run(async() =>
            {
                var are = new AsyncAutoResetEvent();

                are.Set();
                are.Set();
                var task1 = are.WaitAsync();
                var task2 = are.WaitAsync();

                Assert.IsTrue(task1.IsCompleted);
                await AssertEx.NeverCompletesAsync(task2);
            });
        }
Ejemplo n.º 28
0
        public virtual async Task WontKeepMessagesWithNoSubscribersAsync()
        {
            var messageBus = GetMessageBus();

            if (messageBus == null)
            {
                return;
            }

            try {
                await messageBus.PublishAsync(new SimpleMessageA {
                    Data = "Hello"
                });

                await SystemClock.SleepAsync(100);

                var resetEvent = new AsyncAutoResetEvent(false);
                await messageBus.SubscribeAsync <SimpleMessageA>(msg => {
                    Assert.Equal("Hello", msg.Data);
                    resetEvent.Set();
                });

                await Assert.ThrowsAnyAsync <OperationCanceledException>(() => resetEvent.WaitAsync(TimeSpan.FromMilliseconds(100)));
            } finally {
                await CleanupMessageBusAsync(messageBus);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Subscribe to connection packet pipe fore waiting answer packet and then send request
        /// </summary>
        /// <typeparam name="TAnswerPacket"></typeparam>
        /// <typeparam name="TAnswerPayload"></typeparam>
        /// <param name="src"></param>
        /// <param name="packet"></param>
        /// <param name="targetSystem"></param>
        /// <param name="targetComponent"></param>
        /// <param name="cancel"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public static async Task <TAnswerPacket> SendAndWaitAnswer <TAnswerPacket, TAnswerPayload>(this IMavlinkV2Connection src, IPacketV2 <IPayload> packet, int targetSystem, int targetComponent, CancellationToken cancel, Func <TAnswerPacket, bool> filter = null)
            where TAnswerPacket : IPacketV2 <TAnswerPayload>, new() where TAnswerPayload : IPayload
        {
            var         p         = new TAnswerPacket();
            var         eve       = new AsyncAutoResetEvent(false);
            IDisposable subscribe = null;

            filter = filter ?? (_ => true);
            var result = default(TAnswerPacket);

            try
            {
                subscribe = src.Where(_ => _.ComponenId == targetComponent && _.SystemId == targetSystem && _.MessageId == p.MessageId)
                            .Cast <TAnswerPacket>()
                            .FirstAsync(filter)
                            .Subscribe(_ =>
                {
                    result = _;
                    eve.Set();
                });
                await src.Send(packet, cancel).ConfigureAwait(false);

                await eve.WaitAsync(cancel);
            }
            finally
            {
                subscribe?.Dispose();
            }
            return(result);
        }
Ejemplo n.º 30
0
        public void Enqueue(MqttBasePacket packet)
        {
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }

            lock (_queue)
            {
                if (_queue.Count >= _options.MaxPendingMessagesPerClient)
                {
                    if (_options.PendingMessagesOverflowStrategy == MqttPendingMessagesOverflowStrategy.DropNewMessage)
                    {
                        return;
                    }

                    if (_options.PendingMessagesOverflowStrategy == MqttPendingMessagesOverflowStrategy.DropOldestQueuedMessage)
                    {
                        _queue.Dequeue();
                    }
                }

                _queue.Enqueue(packet);
            }

            _queueAutoResetEvent.Set();

            _logger.Verbose("Enqueued packet (ClientId: {0}).", _clientSession.ClientId);
        }
 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);
 }
		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));
		}