System.Threading.WaitHandle.WaitOne(System.TimeSpan)

Here are the examples of the csharp api System.Threading.WaitHandle.WaitOne(System.TimeSpan) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

799 Examples 7

19 View Source File : TcpListenerExtensions.cs
License : MIT License
Project Creator : araditc

public static TcpClient AcceptTcpClient(this TcpListener listener, int timeout) {
			if (timeout == -1)
				return listener.AcceptTcpClient();
			timeout.ThrowIfOutOfRange("timeout", 0, Int32.MaxValue);
			IAsyncResult ar = listener.BeginAcceptTcpClient(null, null);
			bool signalled = ar.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeout));
			if (signalled)
				return listener.EndAcceptTcpClient(ar);
			throw new TimeoutException("The operation timed out.");
		}

19 View Source File : ImapBase.cs
License : Apache License 2.0
Project Creator : azanov

private void ProcessIdleServerEvents()
        {
            while (true)
            {
                string tmp;
                if (!_idleEvents.TryDequeue(out tmp))
                {
                    if (_idleState == IdleState.On)
                    {
                        // instead of an instant retry: wait for a signal that will be emitted after a new value was put into the queue
                        _idleEventsResetEvent.WaitOne();
                        continue;
                    }
                    return;
                }


                Match match = Expressions.IdleResponseRex.Match(tmp);

                if (!match.Success)
                    continue;

                if (match.Groups[2].Value == "EXISTS")
                {
                    SelectedFolder.Status(new[] {FolderStatusFields.UIdNext});

                    if (_lastIdleUId != SelectedFolder.UidNext)
                    {
                        var msgs =
                            SelectedFolder.Search(string.Format("UID {0}:{1}", _lastIdleUId, SelectedFolder.UidNext));
                        var args = new IdleEventArgs
                        {
                            Folder = SelectedFolder,
                            Messages = msgs
                        };
                        if (OnNewMessagesArrived != null)
                            OnNewMessagesArrived(SelectedFolder, args);
                        SelectedFolder.RaiseNewMessagesArrived(args);
                        _lastIdleUId = SelectedFolder.UidNext;
                    }
                }
            }
        }

19 View Source File : ConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000), Ignore("Ignore")]
        public async Task TestMessageListenerClosesItsConsumer()
        {
            var latch = new ManualResetEvent(false);
            var exceptionListenerFired = new ManualResetEvent(false);
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);
                await connection.StartAsync();

                connection.ExceptionListener += _ => exceptionListenerFired.Set();

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = await session.GetQueueAsync("myQueue");
                await connection.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1);

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                testPeer.ExpectLinkFlow(drain: true, sendDrainFlowResponse: true, creditMatcher: credit => replacedert.AreEqual(99, credit)); // Not sure if expected credit is right
                testPeer.ExpectDispositionThatIsAcceptedAndSettled();
                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);

                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        consumer.Close();
                        latch.Set();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(1000)), "Process not completed within given timeout");
                replacedert.IsNull(exception, "No error expected during close");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                replacedert.False(exceptionListenerFired.WaitOne(20), "Exception listener shouldn't have fired");
                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : ConnectionIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestRemotelyEndConnectionListenerInvoked()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent done = new ManualResetEvent(false);

                // Don't set a ClientId, so that the underlying AMQP connection isn't established yet
                IConnection connection = EstablishConnection(testPeer: testPeer, setClientId: false);

                // Tell the test peer to close the connection when executing its last handler
                testPeer.RemotelyCloseConnection(expectCloseResponse: true, errorCondition: ConnectionError.CONNECTION_FORCED, errorMessage: "buba");

                connection.ExceptionListener += exception => done.Set();

                // Trigger the underlying AMQP connection
                connection.Start();

                replacedert.IsTrue(done.WaitOne(TimeSpan.FromSeconds(5)), "Connection should report failure");

                connection.Close();
            }
        }

19 View Source File : ConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestConnectionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);
                await connection.StartAsync();

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = await session.GetQueueAsync("myQueue");
                await connection.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : NMSConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestConsumerCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                context.Start();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                consumer.Close();

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : HttpListenerRequest.cs
License : GNU Affero General Public License v3.0
Project Creator : AugustToko

internal bool FlushInput ()
    {
      if (!HasEnreplacedyBody)
        return true;

      var length = 2048;
      if (_contentLength > 0)
        length = (int) Math.Min (_contentLength, (long) length);

      var buff = new byte [length];
      while (true) {
        // TODO: Test if MS has a timeout when doing this.
        try {
          var ares = InputStream.BeginRead (buff, 0, length, null, null);
          if (!ares.IsCompleted && !ares.AsyncWaitHandle.WaitOne (100))
            return false;

          if (InputStream.EndRead (ares) <= 0)
            return true;
        }
        catch {
          return false;
        }
      }
    }

19 View Source File : ConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000), Ignore("Ignore")]
        public void TestMessageListenerClosesItsConsumer()
        {
            var latch = new ManualResetEvent(false);
            var exceptionListenerFired = new ManualResetEvent(false);
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = EstablishConnection(testPeer);
                connection.Start();

                connection.ExceptionListener += _ => exceptionListenerFired.Set();

                testPeer.ExpectBegin();

                ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = session.GetQueue("myQueue");
                connection.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                testPeer.ExpectLinkFlow(drain: true, sendDrainFlowResponse: true, creditMatcher: credit => replacedert.AreEqual(99, credit)); // Not sure if expected credit is right
                testPeer.ExpectDispositionThatIsAcceptedAndSettled();
                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);

                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        consumer.Close();
                        latch.Set();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(1000)), "Process not completed within given timeout");
                replacedert.IsNull(exception, "No error expected during close");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                connection.Close();

                replacedert.False(exceptionListenerFired.WaitOne(20), "Exception listener shouldn't have fired");
                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : GovernorDaemon.cs
License : MIT License
Project Creator : azist

private void threadBody()
    {
      const int SLICE_MS_LOW = 150;
      const int SLICE_MS_HIGH = 250;

      var rel = Guid.NewGuid();

      try
      {
        startAll(rel);
      }
      catch (Exception error)
      {
        WriteLogFromHere(MessageType.CatastrophicError, "..startAll() leaked: " + error.ToMessageWithType(), error, related: rel);
      }

      while (Running) //<--- LOOP ---
      {
        try
        {
          screplacedlOnce(rel);
        }
        catch(Exception error)
        {
          WriteLogFromHere(MessageType.CatastrophicError, "..screplacedlOnce() leaked: " + error.ToMessageWithType(), error, related: rel);
        }

        m_Wait.WaitOne(Ambient.Random.NextScaledRandomInteger(SLICE_MS_LOW, SLICE_MS_HIGH));
      }//while

      try
      {
        stopAll(rel);
      }
      catch (Exception error)
      {
        WriteLogFromHere(MessageType.CatastrophicError, "stopAll() leaked: " + error.ToMessageWithType(), error, related: rel);
      }
    }

19 View Source File : ConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestConsumerCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = EstablishConnection(testPeer);
                connection.Start();

                testPeer.ExpectBegin();

                ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = session.GetQueue("myQueue");
                connection.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                consumer.Close();

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                connection.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : ProducerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestRemotelyCloseProducer()
        {
            string breadCrumb = "ErrorMessageBreadCrumb";

            ManualResetEvent producerClosed = new ManualResetEvent(false);
            Mock<INmsConnectionListener> mockConnectionListener = new Mock<INmsConnectionListener>();
            mockConnectionListener
                .Setup(listener => listener.OnProducerClosed(It.IsAny<NmsMessageProducer>(), It.IsAny<Exception>()))
                .Callback(() => { producerClosed.Set(); });

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                NmsConnection connection = (NmsConnection) await EstablishConnectionAsync(testPeer);
                connection.AddConnectionListener(mockConnectionListener.Object);

                testPeer.ExpectBegin();
                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);

                // Create a producer, then remotely end it afterwards.
                testPeer.ExpectSenderAttach();
                testPeer.RemotelyDetachLastOpenedLinkOnLastOpenedSession(expectDetachResponse: true, closed: true, errorType: AmqpError.RESOURCE_DELETED, breadCrumb, delayBeforeSend: 10);

                IQueue destination = await session.GetQueueAsync("myQueue");
                IMessageProducer producer = await session.CreateProducerAsync(destination);

                // Verify the producer gets marked closed
                testPeer.WaitForAllMatchersToComplete(1000);

                replacedert.True(producerClosed.WaitOne(TimeSpan.FromMilliseconds(1000)), "Producer closed callback didn't trigger");
                replacedert.That(() => producer.DisableMessageID, Throws.Exception.InstanceOf<IllegalStateException>(), "Producer never closed");

                // Try closing it explicitly, should effectively no-op in client.
                // The test peer will throw during close if it sends anything.
                await producer.CloseAsync();
            }
        }

19 View Source File : NMSConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000), Ignore("Ignore")]
        public async Task TestMessageListenerClosesItsConsumer()
        {
            var latch = new ManualResetEvent(false);
            var exceptionListenerFired = new ManualResetEvent(false);
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);
                await context.StartAsync();

                context.ExceptionListener += _ => exceptionListenerFired.Set();

                testPeer.ExpectBegin();

                IQueue destination = await context.GetQueueAsync("myQueue");
                await context.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1);

                var consumer = await context.CreateConsumerAsync(destination);

                testPeer.ExpectLinkFlow(drain: true, sendDrainFlowResponse: true, creditMatcher: credit => replacedert.AreEqual(99, credit)); // Not sure if expected credit is right
                testPeer.ExpectDispositionThatIsAcceptedAndSettled();
                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);

                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        consumer.Close();
                        latch.Set();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(1000)), "Process not completed within given timeout");
                replacedert.IsNull(exception, "No error expected during close");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                replacedert.False(exceptionListenerFired.WaitOne(20), "Exception listener shouldn't have fired");
                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : ConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestSessionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = EstablishConnection(testPeer);
                connection.Start();

                testPeer.ExpectBegin();

                ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = session.GetQueue("myQueue");
                connection.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectEnd();
                session.Close();

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                connection.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : NMSConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestRecoverOrderingWithAsyncConsumer()
        {
            ManualResetEvent latch = new ManualResetEvent(false);
            Exception asyncError = null;

            int recoverCount = 5;
            int messageCount = 8;
            int testPayloadLength = 255;
            string payload = Encoding.UTF8.GetString(new byte[testPayloadLength]);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer, acknowledgementMode:AcknowledgementMode.ClientAcknowledge);
                context.Start();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(
                    message: new Amqp.Message() { BodySection = new AmqpValue() { Value = payload } },
                    count: messageCount,
                    drain: false,
                    nextIncomingId: 1,
                    addMessageNumberProperty: true,
                    sendDrainFlowResponse: false,
                    sendSettled: false,
                    creditMatcher: credit => replacedert.Greater(credit, messageCount)
                );

                var consumer = context.CreateConsumer(destination);
                
                bool complete = false;
                int messageSeen = 0;
                int expectedIndex = 0;
                consumer.Listener += message =>
                {
                    if (complete)
                    {
                        return;
                    }

                    try
                    {
                        int actualIndex = message.Properties.GetInt(TestAmqpPeer.MESSAGE_NUMBER);
                        replacedert.AreEqual(expectedIndex, actualIndex, "Received Message Out Of Order");

                        // don't ack the message until we receive it X times
                        if (messageSeen < recoverCount)
                        {
                            context.Recover();
                            messageSeen++;
                        }
                        else
                        {
                            messageSeen = 0;
                            expectedIndex++;

                            // Have the peer expect the accept the disposition (1-based, hence pre-incremented).
                            testPeer.ExpectDisposition(settled: true,
                                stateMatcher: state => replacedert.AreEqual(state.Descriptor.Code, MessageSupport.ACCEPTED_INSTANCE.Descriptor.Code
                                ));

                            message.Acknowledge();

                            if (expectedIndex == messageCount)
                            {
                                complete = true;
                                latch.Set();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        complete = true;
                        asyncError = e;
                        latch.Set();
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromSeconds(15)), "Messages not received within given timeout.");
                replacedert.IsNull(asyncError, "Unexpected exception");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : SkinnedState.cs
License : MIT License
Project Creator : AmplifyCreations

private void WaitForAsyncUpdate()
	{
		if ( m_asyncUpdateTriggered )
		{
			if ( !m_asyncUpdateSignal.WaitOne( MotionState.AsyncUpdateTimeout ) )
			{
				Debug.LogWarning( "[AmplifyMotion] Aborted abnormally long Async Skin deform operation. Not a critical error but might indicate a problem. Please contact support." );
				return;
			}
			m_asyncUpdateTriggered = false;
		}
	}

19 View Source File : SocketHelper.cs
License : Apache License 2.0
Project Creator : aryice

public static bool TestConnection(string host, int port, int millisecondsTimeout)
        {
            TcpClient client = new TcpClient();
            try
            {
                var ar = client.BeginConnect(host, port, null, null);
                ar.AsyncWaitHandle.WaitOne(millisecondsTimeout);
                return client.Connected;
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                client.Close();
            }
        }

19 View Source File : ConnectionIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestExplicitConnectionCloseListenerIsNotInvoked()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent exceptionFired = new ManualResetEvent(false);
                IConnection connection = await EstablishConnectionAsync(testPeer);
                connection.ExceptionListener += exception => { exceptionFired.Set(); };
                
                testPeer.ExpectClose();
                await connection.CloseAsync();
                
                replacedert.IsFalse(exceptionFired.WaitOne(TimeSpan.FromMilliseconds(100)));
            }
        }

19 View Source File : SystemsManagerConfigurationProvider.cs
License : Apache License 2.0
Project Creator : aws

public void WaitForReloadToComplete(TimeSpan timeout)
        {
            ReloadTaskEvent.WaitOne(timeout);
        }

19 View Source File : Worker.cs
License : MIT License
Project Creator : actions

private void Worker_Unloading(object sender, EventArgs e)
        {
            if (!HostContext.RunnerShutdownToken.IsCancellationRequested)
            {
                HostContext.ShutdownRunner(ShutdownReason.UserCancelled);
                _completedCommand.WaitOne(Constants.Runner.ExitOnUnloadTimeout);
            }
        }

19 View Source File : LocalCache.cs
License : MIT License
Project Creator : azist

private void threadSpin()
        {
              var lastPileCompact = DateTime.UtcNow;

              WriteLog(MessageType.Info, "threadSpin()", "Entering...");
              try
              {
                  var wasActive = App.Active;//remember whether app was active during start
                                             //this is needed so that CacheStore works without app container (using NOPApplication) in which case
                                             //service must be .Disposed() to stop this thread
                  var timer = Stopwatch.StartNew();
                  while ((App.Active | !wasActive) && Running)
                  {
                    var utcNow = DateTime.UtcNow;

                    var tc = m_Tables.Count;
                    var maxTimePerTableMs = THREAD_MAX_TIME_FOR_SWEEP_ALL_MS / (tc!=0 ? tc : 1);
                    if (maxTimePerTableMs<2) maxTimePerTableMs = 2;

                    foreach(var table in m_Tables)
                    {
                       if (!Running) break;
                       try
                       {
                         var sweptToEnd = table.Sweep(timer, maxTimePerTableMs);
                         if (m_InstrumentationEnabled)
                         {
                           Instrumentation.CacheTableSwept.Happened(App.Instrumentation, Name); //for cache
                           Instrumentation.CacheTableSwept.Happened(App.Instrumentation, Name+"."+table.Name); //for table
                         }

                         if (sweptToEnd)
                         {
                           if (table.Count==0)
                           {
                               if (!table.SweepWhenBecameEmpty.HasValue)
                                 table.SweepWhenBecameEmpty = utcNow;
                               else
                                if ((utcNow - table.SweepWhenBecameEmpty.Value).TotalSeconds > EMPTY_TABLE_LIFE_SEC)
                                {
                                  m_Tables.Unregister(table);//can mutate m_Tables because foreach does a snapshot via GetEnumerator
                                }
                           }
                           else
                            table.SweepWhenBecameEmpty = null;
                         }
                       }
                       catch(Exception error)
                       {
                         WriteLog(MessageType.Critical,
                             "threadSpin().foreach.Sweep",
                             "Leaked exception while sweeping table '{0}': {1}'"
                               .Args(table.Name, error.ToMessageWithType()), error );
                       }
                    }


                    try
                    {
                      dumpInstruments();
                    }
                    catch(Exception error)
                    {
                         WriteLog(MessageType.Critical,
                             "threadSpin().dumpInstruments",
                             "Leaked exception dumping instrumentation: {0}'"
                               .Args(error.ToMessageWithType()), error );
                    }

                    try
                    {

                      if ((utcNow-lastPileCompact).TotalSeconds > 5 * 60)
                      {
                         var freed = m_Pile.Compact();
                         lastPileCompact = utcNow;
                         if (freed>0)
                          WriteLog(MessageType.Info, "threadSpin().pile.compact()", "Freed {0:n0} bytes".Args(freed));
                      }
                    }
                    catch(Exception error)
                    {
                         WriteLog(MessageType.Critical,
                             "threadSpin().pile.compact()",
                             "Leaked exception compacting pile: {0}'"
                               .Args(error.ToMessageWithType()), error );
                    }

                    m_Trigger.WaitOne(THREAD_MIN_GRANULARITY_MS + App.Random.NextScaledRandomInteger(0, THREAD_GRANULARITY_VARIANCE_MS));
                  }//while

              }
              catch(Exception e)
              {
                  WriteLog(MessageType.Emergency, "threadSpin()", "Leaked exception, the tables are not swept anymore"+e.ToMessageWithType(), e);
              }

              WriteLog(MessageType.Info, "threadSpin()", "...Exiting");
        }

19 View Source File : ConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestConsumerCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);
                await connection.StartAsync();

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = await session.GetQueueAsync("myQueue");
                await connection.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                await consumer.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : ConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestSessionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);
                await connection.StartAsync();

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = await session.GetQueueAsync("myQueue");
                await connection.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectEnd();
                await session.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : SuperIndexer.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

public void EndTransaction()
        {
            Task.Run(async () =>
            {
                Debug.WriteLine("Ending Super Indexer Transaction...");

                var result = this.WaitingOnGroupAndChatListings.WaitOne(TimeSpan.FromSeconds(10));

                if (!result)
                {
                    Debug.WriteLine("No group list available, loading new...");

                    var client = this.GroupsAndChats.FirstOrDefault()?.Client;
                    if (client == null)
                    {
                        return;
                    }

                    await client.GetGroupsAsync();
                    await client.GetChatsAsync();
                    this.GroupsAndChats = Enumerable.Concat<IMessageContainer>(client.Groups(), client.Chats());
                }

                this.OutdatedGroupIdList = this.CheckForOutdatedCache(this.GroupsAndChats);

                Debug.WriteLine("Dirty groups computed, count " + this.OutdatedGroupIdList.Count);

                using (var context = this.CacheManager.OpenNewContext())
                {
                    // Update Group and Chat metadata in cache
                    if (DateTime.Now.Subtract(this.LastMetadataUpdate) > this.SettingsManager.CoreSettings.MetadataCacheInterval)
                    {
                        this.LastMetadataUpdate = DateTime.Now;

                        // Remove old metadata. Doing a removal and addition in the same cycle was causing
                        // OtherUserId foreign key for Chats to be null. Doing true updates with cascading deletes
                        // should be possible, but this can be done easily in SQLite without any further migrations (GMDC 33.0.3)
                        foreach (var metaData in this.GroupsAndChats)
                        {
                            if (metaData is Group groupMetadata)
                            {
                                var existing = context.GroupMetadata
                                    .Include(g => g.Members)
                                    .FirstOrDefault(g => g.Id == groupMetadata.Id);
                                if (existing != null)
                                {
                                    foreach (var member in existing.Members)
                                    {
                                        context.Remove(member);
                                    }

                                    context.GroupMetadata.Remove(existing);
                                }
                            }
                            else if (metaData is Chat chatMetadata)
                            {
                                var existingChat = context.ChatMetadata.FirstOrDefault(c => c.Id == metaData.Id);
                                if (existingChat != null)
                                {
                                    context.Remove(existingChat);
                                }

                                var existingMember = context.Find<Member>(chatMetadata.OtherUser.Id);
                                if (existingMember != null)
                                {
                                    context.Remove(existingMember);
                                }
                            }
                        }

                        context.SaveChanges();

                        foreach (var addMetaData in this.GroupsAndChats)
                        {
                            context.Add(addMetaData);
                        }

                        context.SaveChanges();
                    }

                    // Process updates for each group and chat
                    var fullyUpdatedGroupIds = new List<string>();
                    foreach (var id in this.GroupUpdates.Keys)
                    {
                        var messages = this.GroupUpdates[id];
                        var groupState = context.IndexStatus.Find(id);
                        if (groupState == null)
                        {
                            // No cache status exists for this group. Force a full re-index.
                        }
                        else if (this.OutdatedGroupIdList.Contains(id))
                        {
                            var availableMessageIds = messages.Select(m => long.Parse(m.Id)).ToList();
                            var messageContainer = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);

                            long.TryParse(groupState.LastIndexedId, out var lastIndexId);
                            if (availableMessageIds.Contains(lastIndexId))
                            {
                                // All new messages have already been loaded and are ready to index.
                                var newMessages = new List<Message>();
                                var newLastIndexId = lastIndexId;
                                foreach (var msg in messages)
                                {
                                    if (long.TryParse(msg.Id, out var messageId) && messageId > lastIndexId)
                                    {
                                        newMessages.Add(msg);

                                        if (messageId > newLastIndexId)
                                        {
                                            newLastIndexId = messageId;
                                        }
                                    }
                                }

                                context.AddMessages(newMessages);
                                groupState.LastIndexedId = newLastIndexId.ToString();
                                context.SaveChanges();
                                fullyUpdatedGroupIds.Add(id);
                            }
                        }
                    }

                    Debug.WriteLine("In place deltas applied, resolved " + fullyUpdatedGroupIds.Count);

                    // Preplaced 2, go through all originally outdated chats and run the complete re-index task on them
                    // if they couldn't be automatically updated with available messages.
                    foreach (var id in this.OutdatedGroupIdList)
                    {
                        if (!fullyUpdatedGroupIds.Contains(id))
                        {
                            var container = this.GroupsAndChats.FirstOrDefault(c => c.Id == id);
                            var cts = new CancellationTokenSource();

                            Debug.WriteLine("Full index scan required for " + container.Name);

                            // Don't start multiple overlapping indexing tasks.
                            var existingScan = this.TaskManager.RunningTasks.FirstOrDefault(t => t.Tag == id);
                            if (existingScan == null)
                            {
                                this.TaskManager.AddTask(
                                    $"Indexing {container.Name}",
                                    id,
                                    this.IndexGroup(container, cts),
                                    cts);
                            }
                        }
                    }
                }

                this.GroupUpdates.Clear();
                this.WaitingOnGroupAndChatListings.Reset();
            });
        }

19 View Source File : MessageExpirationIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestIncomingExpiredMessageGetsFilteredAsync()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);
                await connection.StartAsync();

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.AutoAcknowledge);
                IQueue queue = await session.GetQueueAsync("myQueue");

                // Expected the consumer to attach and send credit, then send it an
                // already-expired message followed by a live message.
                testPeer.ExpectReceiverAttach();

                string expiredMsgContent = "already-expired";
                Amqp.Message message = CreateExpiredMessage(expiredMsgContent);
                testPeer.ExpectLinkFlowRespondWithTransfer(message: message);

                string liveMsgContent = "valid";
                testPeer.SendTransferToLastOpenedLinkOnLastOpenedSession(message: new Amqp.Message() { BodySection = new AmqpValue() { Value = liveMsgContent } }, nextIncomingId: 2);

                IMessageConsumer consumer = await session.CreateConsumerAsync(queue);

                // Add message listener, expect the first message to be filtered due to expiry,
                // and the second message to be given to the test app and accepted.
                Action<DeliveryState> modifiedMatcher = state =>
                {
                    var modified = state as Modified;
                    replacedert.IsNotNull(modified);
                    replacedert.IsTrue(modified.DeliveryFailed);
                    replacedert.IsTrue(modified.UndeliverableHere);
                };
                testPeer.ExpectDisposition(settled: true, stateMatcher: modifiedMatcher, firstDeliveryId: 1, lastDeliveryId: 1);
                testPeer.ExpectDisposition(settled: true, stateMatcher: replacedert.IsInstanceOf<Accepted>, firstDeliveryId: 2, lastDeliveryId: 2);


                ManualResetEvent success = new ManualResetEvent(false);
                ManualResetEvent listenerFailure = new ManualResetEvent(false);

                consumer.Listener += m =>
                {
                    if (liveMsgContent.Equals(((ITextMessage) m).Text))
                        success.Set();
                    else
                        listenerFailure.Set();
                };

                replacedert.True(success.WaitOne(TimeSpan.FromSeconds(5)), "didn't get expected message");
                replacedert.False(listenerFailure.WaitOne(TimeSpan.FromMilliseconds(100)), "Received message when message should not have been received");

                testPeer.WaitForAllMatchersToComplete(3000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(3000);
            }
        }

19 View Source File : ConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestConnectionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = EstablishConnection(testPeer);
                connection.Start();

                testPeer.ExpectBegin();

                ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IQueue destination = session.GetQueue("myQueue");
                connection.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectClose();
                connection.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : NMSConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestSessionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);
                await context.StartAsync();

                testPeer.ExpectBegin();

                IQueue destination = await context.GetQueueAsync("myQueue");
                await context.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                var consumer = await context.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                
                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : NMSConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestRecoverOrderingWithAsyncConsumer()
        {
            ManualResetEvent latch = new ManualResetEvent(false);
            Exception asyncError = null;

            int recoverCount = 5;
            int messageCount = 8;
            int testPayloadLength = 255;
            string payload = Encoding.UTF8.GetString(new byte[testPayloadLength]);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer, acknowledgementMode:AcknowledgementMode.ClientAcknowledge);
                await context.StartAsync();

                testPeer.ExpectBegin();

                IQueue destination = await context.GetQueueAsync("myQueue");
                await context.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(
                    message: new Amqp.Message() { BodySection = new AmqpValue() { Value = payload } },
                    count: messageCount,
                    drain: false,
                    nextIncomingId: 1,
                    addMessageNumberProperty: true,
                    sendDrainFlowResponse: false,
                    sendSettled: false,
                    creditMatcher: credit => replacedert.Greater(credit, messageCount)
                );

                var consumer = await context.CreateConsumerAsync(destination);
                
                bool complete = false;
                int messageSeen = 0;
                int expectedIndex = 0;
                consumer.Listener += message =>
                {
                    if (complete)
                    {
                        return;
                    }

                    try
                    {
                        int actualIndex = message.Properties.GetInt(TestAmqpPeer.MESSAGE_NUMBER);
                        replacedert.AreEqual(expectedIndex, actualIndex, "Received Message Out Of Order");

                        // don't ack the message until we receive it X times
                        if (messageSeen < recoverCount)
                        {
                            context.Recover();
                            messageSeen++;
                        }
                        else
                        {
                            messageSeen = 0;
                            expectedIndex++;

                            // Have the peer expect the accept the disposition (1-based, hence pre-incremented).
                            testPeer.ExpectDisposition(settled: true,
                                stateMatcher: state => replacedert.AreEqual(state.Descriptor.Code, MessageSupport.ACCEPTED_INSTANCE.Descriptor.Code
                                ));

                            message.Acknowledge();

                            if (expectedIndex == messageCount)
                            {
                                complete = true;
                                latch.Set();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        complete = true;
                        asyncError = e;
                        latch.Set();
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromSeconds(15)), "Messages not received within given timeout.");
                replacedert.IsNull(asyncError, "Unexpected exception");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : NMSConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestConnectionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                context.Start();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : ConnectionIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestExplicitConnectionCloseListenerIsNotInvoked()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent exceptionFired = new ManualResetEvent(false);
                IConnection connection = EstablishConnection(testPeer);
                connection.ExceptionListener += exception => { exceptionFired.Set(); };
                
                testPeer.ExpectClose();
                connection.Close();
                
                replacedert.IsFalse(exceptionFired.WaitOne(TimeSpan.FromMilliseconds(100)));
            }
        }

19 View Source File : UdpTracker.cs
License : MIT License
Project Creator : aljazsim

private TrackerMessage ExecuteUdpRequest(Uri uri, TrackerMessage message)
        {
            uri.CannotBeNull();
            message.CannotBeNull();

            byte[] data = null;
            IAsyncResult asyncResult;
            IPEndPoint any = new IPEndPoint(IPAddress.Any, this.ListeningPort);

            try
            {
                using (UdpClient udp = new UdpClient())
                {
                    udp.Client.SendTimeout = (int)TimeSpan.FromSeconds(5).TotalMilliseconds;
                    udp.Client.ReceiveTimeout = (int)TimeSpan.FromSeconds(15).TotalMilliseconds;

                    udp.Send(message.Encode(), message.Length, this.TrackerUri.Host, this.TrackerUri.Port);

                    asyncResult = udp.BeginReceive(null, null);

                    if (asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
                    {
                        data = udp.EndReceive(asyncResult, ref any);
                    }
                    else
                    {
                        // timeout
                    }
                }
            }
            catch (SocketException ex)
            {
                Debug.WriteLine($"could not send message to UDP tracker {this.TrackerUri} for torrent {this.TorrentInfoHash}: {ex.Message}");

                return null;
            }

            if (TrackerMessage.TryDecode(data, 0, MessageType.Response, out message))
            {
                if (message is ErrorMessage)
                {
                    Debug.WriteLine($"error message received from UDP tracker {this.TrackerUri}: \"{message.As<ErrorMessage>().ErrorText}\"");
                }

                return message;
            }
            else
            {
                return null;
            }
        }

19 View Source File : NMSConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000), Ignore("Ignore")]
        public void TestMessageListenerClosesItsConsumer()
        {
            var latch = new ManualResetEvent(false);
            var exceptionListenerFired = new ManualResetEvent(false);
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                context.Start();

                context.ExceptionListener += _ => exceptionListenerFired.Set();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectLinkFlow(drain: true, sendDrainFlowResponse: true, creditMatcher: credit => replacedert.AreEqual(99, credit)); // Not sure if expected credit is right
                testPeer.ExpectDispositionThatIsAcceptedAndSettled();
                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);

                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        consumer.Close();
                        latch.Set();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(1000)), "Process not completed within given timeout");
                replacedert.IsNull(exception, "No error expected during close");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                replacedert.False(exceptionListenerFired.WaitOne(20), "Exception listener shouldn't have fired");
                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : MessageExpirationIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestIncomingExpiredMessageGetsFilteredAsync()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = EstablishConnection(testPeer);
                connection.Start();

                testPeer.ExpectBegin();

                ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);
                IQueue queue = session.GetQueue("myQueue");

                // Expected the consumer to attach and send credit, then send it an
                // already-expired message followed by a live message.
                testPeer.ExpectReceiverAttach();

                string expiredMsgContent = "already-expired";
                Amqp.Message message = CreateExpiredMessage(expiredMsgContent);
                testPeer.ExpectLinkFlowRespondWithTransfer(message: message);

                string liveMsgContent = "valid";
                testPeer.SendTransferToLastOpenedLinkOnLastOpenedSession(message: new Amqp.Message() { BodySection = new AmqpValue() { Value = liveMsgContent } }, nextIncomingId: 2);

                IMessageConsumer consumer = session.CreateConsumer(queue);

                // Add message listener, expect the first message to be filtered due to expiry,
                // and the second message to be given to the test app and accepted.
                Action<DeliveryState> modifiedMatcher = state =>
                {
                    var modified = state as Modified;
                    replacedert.IsNotNull(modified);
                    replacedert.IsTrue(modified.DeliveryFailed);
                    replacedert.IsTrue(modified.UndeliverableHere);
                };
                testPeer.ExpectDisposition(settled: true, stateMatcher: modifiedMatcher, firstDeliveryId: 1, lastDeliveryId: 1);
                testPeer.ExpectDisposition(settled: true, stateMatcher: replacedert.IsInstanceOf<Accepted>, firstDeliveryId: 2, lastDeliveryId: 2);


                ManualResetEvent success = new ManualResetEvent(false);
                ManualResetEvent listenerFailure = new ManualResetEvent(false);

                consumer.Listener += m =>
                {
                    if (liveMsgContent.Equals(((ITextMessage) m).Text))
                        success.Set();
                    else
                        listenerFailure.Set();
                };

                replacedert.True(success.WaitOne(TimeSpan.FromSeconds(5)), "didn't get expected message");
                replacedert.False(listenerFailure.WaitOne(TimeSpan.FromMilliseconds(100)), "Received message when message should not have been received");

                testPeer.WaitForAllMatchersToComplete(3000);

                testPeer.ExpectClose();
                connection.Close();

                testPeer.WaitForAllMatchersToComplete(3000);
            }
        }

19 View Source File : EventBus.cs
License : MIT License
Project Creator : apirker

public U PublishRequestAndWait<T, U>(T requestEvent)
            where T : IEvent
            where U : IEventResponse
        {
            var waithandle = new AutoResetEvent(false);
            var callback = new ResponseEventAndMutex(waithandle);
            mutexDictionary.Add(requestEvent.EventId, callback);

            var responseEventHandler = new ResponseEventHandler<U>(this);
            Subscribe<U>(responseEventHandler);
            Start();

            Publish(requestEvent);

            waithandle.WaitOne(options.MaxResponseWaitingTime);

            Unsubscribe<U>(responseEventHandler);
            mutexDictionary.Remove(requestEvent.EventId);
            if (callback.Response == null)
                throw new InvalidOperationException();

            return (U)callback.Response;
        }

19 View Source File : Runner.cs
License : MIT License
Project Creator : actions

private void Runner_Unloading(object sender, EventArgs e)
        {
            if ((!_inConfigStage) && (!HostContext.RunnerShutdownToken.IsCancellationRequested))
            {
                HostContext.ShutdownRunner(ShutdownReason.UserCancelled);
                _completedCommand.WaitOne(Constants.Runner.ExitOnUnloadTimeout);
            }
        }

19 View Source File : ApiIntervalUpdateTrigger.cs
License : MIT License
Project Creator : Archomeda

private void PresenceLoopThread()
        {
            while (!this.cancelSource.Token.IsCancellationRequested)
            {
                if (string.IsNullOrWhiteSpace(this.ApiToken))
                    return;

                TimeSpan timeToWait = TimeSpan.FromSeconds(fallbackRefreshRate);
                try
                {
                    var playerInfo = SaliensApi.GetPlayerInfo(this.ApiToken);
                    this.presence.Logger?.LogMessage($"Updating Discord presence with {playerInfo.Score} XP");
                    this.presence.SetSaliensPlayerState(playerInfo);
                    if (!string.IsNullOrWhiteSpace(playerInfo.ActiveZonePosition))
                    {
                        if (playerInfo.TimeInZone < TimeSpan.FromSeconds(110))
                            timeToWait = TimeSpan.FromSeconds(110) - playerInfo.TimeInZone;
                        else if (playerInfo.TimeInZone < TimeSpan.FromSeconds(120))
                            timeToWait = TimeSpan.FromSeconds(120) - playerInfo.TimeInZone;
                        timeToWait += TimeSpan.FromSeconds(5);
                    }
                }
                catch (Exception ex)
                {
                    this.presence.Logger?.LogException(ex);
                }

                this.cancelSource.Token.WaitHandle.WaitOne(timeToWait);
            }
        }

19 View Source File : ProducerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestRemotelyCloseProducer()
        {
            string breadCrumb = "ErrorMessageBreadCrumb";

            ManualResetEvent producerClosed = new ManualResetEvent(false);
            Mock<INmsConnectionListener> mockConnectionListener = new Mock<INmsConnectionListener>();
            mockConnectionListener
                .Setup(listener => listener.OnProducerClosed(It.IsAny<NmsMessageProducer>(), It.IsAny<Exception>()))
                .Callback(() => { producerClosed.Set(); });

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                NmsConnection connection = (NmsConnection) EstablishConnection(testPeer);
                connection.AddConnectionListener(mockConnectionListener.Object);

                testPeer.ExpectBegin();
                ISession session = connection.CreateSession(AcknowledgementMode.AutoAcknowledge);

                // Create a producer, then remotely end it afterwards.
                testPeer.ExpectSenderAttach();
                testPeer.RemotelyDetachLastOpenedLinkOnLastOpenedSession(expectDetachResponse: true, closed: true, errorType: AmqpError.RESOURCE_DELETED, breadCrumb, delayBeforeSend: 10);

                IQueue destination = session.GetQueue("myQueue");
                IMessageProducer producer = session.CreateProducer(destination);

                // Verify the producer gets marked closed
                testPeer.WaitForAllMatchersToComplete(1000);

                replacedert.True(producerClosed.WaitOne(TimeSpan.FromMilliseconds(1000)), "Producer closed callback didn't trigger");
                replacedert.That(() => producer.DisableMessageID, Throws.Exception.InstanceOf<IllegalStateException>(), "Producer never closed");

                // Try closing it explicitly, should effectively no-op in client.
                // The test peer will throw during close if it sends anything.
                producer.Close();
            }
        }

19 View Source File : AddInActivatorProcess.cs
License : MIT License
Project Creator : askguanyu

[EnvironmentPermissionAttribute(SecurityAction.Demand, Unrestricted = true)]
        public void Start()
        {
            this.CheckDisposed();

            this.DisposeClient();

            string guid = Guid.NewGuid().ToString();
            bool isCreated;

            using (EventWaitHandle serverStartedHandle = new EventWaitHandle(false, EventResetMode.ManualReset, string.Format(AddInActivatorHost.AddInDomainEventNameStringFormat, guid), out isCreated))
            {
                if (!isCreated)
                {
                    throw new Exception(AddInConstants.EventHandleAlreadyExistedException);
                }

                string addInDomainreplacedemblyPath = typeof(AddInActivatorProcess).replacedembly.Location;

                AddInDomainSetup.WriteSetupFile(this._addInDomainSetup, this._addInDomainSetupFile);

                //// args[0] = AddInDomain replacedembly path
                //// args[1] = GUID
                //// args[2] = PID
                //// args[3] = AddInDomainSetup file
                //// args[4] = Redirect output or not

                this._process.StartInfo.Arguments = string.Format("\"{0}\" {1} {2} \"{3}\" {4}", addInDomainreplacedemblyPath, guid, Process.GetCurrentProcess().Id.ToString(), this._addInDomainSetupFile, this._redirectOutput.ToString());
                this.IsRunning = this._process.Start();

                if (!this.IsRunning)
                {
                    Debug.WriteLine(string.Format(AddInConstants.ProcessStartExceptionStringFormat, this._process.StartInfo.FileName));
                    throw new Exception(string.Format(AddInConstants.ProcessStartExceptionStringFormat, this._process.StartInfo.FileName));
                }

                if (!serverStartedHandle.WaitOne(this._addInDomainSetup.ProcessStartTimeout))
                {
                    Debug.WriteLine(AddInConstants.ProcessStartTimeoutException);
                    throw new Exception(AddInConstants.ProcessStartTimeoutException);
                }

                this._process.BeginOutputReadLine();
                this._process.BeginErrorReadLine();
                this._process.PriorityClreplaced = this._addInDomainSetup.ProcessPriority;
                this._addInActivatorClient = new AddInActivatorClient(guid, this._addInDomainSetup);
                this.RaiseEvent(this.Attached);
            }
        }

19 View Source File : NMSConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestConnectionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);
                await context.StartAsync();

                testPeer.ExpectBegin();

                IQueue destination = await context.GetQueueAsync("myQueue");
                await context.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                var consumer = await context.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : App.xaml.cs
License : GNU General Public License v3.0
Project Creator : AutoDarkMode

private async void Application_Startup(object sender, StartupEventArgs e)
        {
            List<string> args = new();
            if (e.Args.Length > 0)
            {
                args = new List<string>(e.Args);
            }
            if (args.Count > 0 && args.Contains("/debug"))
            {
                debug = true;
                args.Remove("/debug");
            }

            if (args.Count > 0)
            {
                IMessageClient client = new PipeClient();
                _ = client.SendMessageAndGetReply(args[0]);
                Environment.Exit(-1);
            }

            if (!Mutex.WaitOne(TimeSpan.FromMilliseconds(100)))
            {
                Environment.Exit(-1);
            }

            bool serviceStartIssued = StartService();
            Task serviceStart = Task.Run(() => WaitForServiceStart());

            MainWindow mainWin = null;
            MainWindowMwpf mainWinMwpf = null;

            if (Environment.OSVersion.Version.Build >= 22000)
            {
                mainWinMwpf = new();
            }
            else
            {
                mainWin = new();
            }

            string message = AdmProperties.Resources.StartupLaunchingServiceText;
            MsgBox msg = new(message, AdmProperties.Resources.StartupLaunchingServicereplacedle, "info", "none")
            {
                Owner = null
            };
            if (!Settings.Default.FirstRun && (Settings.Default.Left != 0 || Settings.Default.Top != 0))
            {
                msg.Left = Settings.Default.Left;
                msg.Top = Settings.Default.Top;
            }
            if (serviceStartIssued)
            {
                msg.Show();
            }
            await serviceStart;
            if (serviceStartIssued)
            {
                Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                msg.Close();
                Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
            }


            //only run at first startup
            if (Settings.Default.FirstRun)
            {
                //enable autostart
                AutostartHandler.EnableAutoStart(null);

                //check if system uses 12 hour clock
                SystemTimeFormat();

                //create jump list entries
                AddJumpList();

                //finished first startup code
                Settings.Default.FirstRun = false;
            }
            else
            {
                // validate autostart always if firstrun has completed
                AutostartHandler.EnsureAutostart(null);
            }

            //run if user changed language in previous session
            if (Settings.Default.LanguageChanged)
            {
                AddJumpList();
                Settings.Default.LanguageChanged = false;
            }


            if (mainWin != null)
            {
                mainWin.Show();
            }
            else
            {
                mainWinMwpf.Show();
            }
        }

19 View Source File : ConnectionIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestRemotelyEndConnectionListenerInvoked()
        {
            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent done = new ManualResetEvent(false);

                // Don't set a ClientId, so that the underlying AMQP connection isn't established yet
                IConnection connection = await EstablishConnectionAsync(testPeer: testPeer, setClientId: false);

                // Tell the test peer to close the connection when executing its last handler
                testPeer.RemotelyCloseConnection(expectCloseResponse: true, errorCondition: ConnectionError.CONNECTION_FORCED, errorMessage: "buba");

                connection.ExceptionListener += exception => done.Set();

                // Trigger the underlying AMQP connection
                await connection.StartAsync();

                replacedert.IsTrue(done.WaitOne(TimeSpan.FromSeconds(5)), "Connection should report failure");

                await connection.CloseAsync();
            }
        }

19 View Source File : DependentEventSource.cs
License : Apache License 2.0
Project Creator : awslabs

private void PollForDependency(CancellationToken token)
        {
            try
            {
                while (!_dependency.IsDependencyAvailable() && !token.IsCancellationRequested)
                {
                    try
                    {
                        if (!_dependencyFailStart.HasValue)
                        {
                            _dependencyFailStart = DateTime.UtcNow;
                        }
                        if (!_dependencyFailLastReported.HasValue)
                        {
                            _logger?.LogError($"Dependent {_dependency.Name} is not available so no events can be collected for source {Id}. Will check again in {DelayBetweenDependencyPoll.TotalSeconds} seconds.");
                            _dependencyFailLastReported = DateTime.UtcNow;
                        }
                        else if (DateTime.UtcNow - _dependencyFailLastReported.Value > MinimumDelayBetweenDependencyFailureLogging)
                        {
                            _logger?.LogError($"Dependent {_dependency.Name} has not been available for {(DateTime.UtcNow - _dependencyFailStart)}.  "
                                + $"No events have been collected for that period of time. Will check again in {DelayBetweenDependencyPoll.TotalSeconds} seconds.");
                            _dependencyFailLastReported = DateTime.UtcNow;
                        }
                        token.WaitHandle.WaitOne(DelayBetweenDependencyPoll);
                    }
                    catch (Exception e)
                    {
                        _logger?.LogError($"Error during polling of dependent {_dependency.Name} for source {Id}: {e.ToMinimized()}");
                    }
                }
                if (token.IsCancellationRequested)
                {
                    token.ThrowIfCancellationRequested();
                }

                try
                {
                    AfterDependencyAvailable();
                    _logger?.LogInformation($"Dependent {_dependency.Name} is now available and events are being collected.");
                }
                catch (Exception e)
                {
                    _logger?.LogError($"Error invoking AfterDependencyRunning when dependent {_dependency.Name} for source {Id} transitioned to running: {e.ToMinimized()}");
                }
            }
            finally
            {
                _cancellationTokenSource = null;
                _dependencyFailStart = null;
                _dependencyFailLastReported = null;
                _resetInProgress = 0;
            }
        }

19 View Source File : LogManagerTests.cs
License : MIT License
Project Creator : Abc-Arbitrage

[Test]
        public void should_wait_for_event_when_log_event_pool_is_exhausted()
        {
            LogManager.Shutdown();

            BasicConfigurator.Configure(new ZeroLogBasicConfiguration
            {
                Appenders = { _testAppender },
                LogEventQueueSize = 10,
                LogEventPoolExhaustionStrategy = LogEventPoolExhaustionStrategy.WaitForLogEvent
            });

            var log = LogManager.GetLogger(typeof(LogManagerTests));

            var actualLogEvents = new List<ILogEvent>();
            for (var i = 0; i < 10; i++)
            {
                actualLogEvents.Add(log.Debug());
            }

            var signal = _testAppender.SetMessageCountTarget(2);
            var logCompletedSignal = new ManualResetEvent(false);

            Task.Run(() =>
            {
                log.Debug().Append("this is not going to happen").Log();
                logCompletedSignal.Set();
            });

            Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsFalse();

            actualLogEvents[0].Log();

            Check.That(logCompletedSignal.WaitOne(TimeSpan.FromMilliseconds(100))).IsTrue();
            Check.That(signal.Wait(TimeSpan.FromMilliseconds(100))).IsTrue();
        }

19 View Source File : InstrumentationDaemon.cs
License : MIT License
Project Creator : azist

private void threadSpin()
    {
      var rel = Guid.NewGuid();
      var errCount = 0;
      try
      {

        while (Running)
        {

          try
          {
            if (m_SelfInstrumented)
              instrumentSelf();

            write();

            if (m_OSInstrumentationIntervalMS <= 0)
              m_Trigger.WaitOne(m_ProcessingIntervalMS);
            else
              instrumentOS();

            errCount = 0;//success
          }
          catch (Exception bodyError)
          {
            errCount++;
            WriteLog(errCount > 5 ? MessageType.Emergency : errCount > 1 ? MessageType.CriticalAlert : MessageType.Critical,
                     "threadSpin() loop",
                     "Leaked {0} consecutive times Exception: {1}".Args(errCount, bodyError.ToMessageWithType()),
                     error: bodyError,
                     related: rel);

            //progressive throttle
            m_Trigger.WaitOne(2500 + (1000 * errCount.KeepBetween(1, 15)));
          }

        }//while

        write();
      }
      catch (Exception e)
      {
        WriteLog(MessageType.Emergency, " threadSpin()", "Leaked: " + e.ToMessageWithType(), e, related: rel);
      }

      WriteLog(MessageType.Trace, "Exiting threadSpin()", null, related: rel);
    }

19 View Source File : ConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestRecoverOrderingWithAsyncConsumer()
        {
            ManualResetEvent latch = new ManualResetEvent(false);
            Exception asyncError = null;

            int recoverCount = 5;
            int messageCount = 8;
            int testPayloadLength = 255;
            string payload = Encoding.UTF8.GetString(new byte[testPayloadLength]);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = await EstablishConnectionAsync(testPeer);
                await connection.StartAsync();

                testPeer.ExpectBegin();

                ISession session = await connection.CreateSessionAsync(AcknowledgementMode.ClientAcknowledge);
                IQueue destination = await session.GetQueueAsync("myQueue");
                await connection.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(
                    message: new Amqp.Message() { BodySection = new AmqpValue() { Value = payload } },
                    count: messageCount,
                    drain: false,
                    nextIncomingId: 1,
                    addMessageNumberProperty: true,
                    sendDrainFlowResponse: false,
                    sendSettled: false,
                    creditMatcher: credit => replacedert.Greater(credit, messageCount)
                );

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                bool complete = false;
                int messageSeen = 0;
                int expectedIndex = 0;
                consumer.Listener += message =>
                {
                    if (complete)
                    {
                        return;
                    }

                    try
                    {
                        int actualIndex = message.Properties.GetInt(TestAmqpPeer.MESSAGE_NUMBER);
                        replacedert.AreEqual(expectedIndex, actualIndex, "Received Message Out Of Order");

                        // don't ack the message until we receive it X times
                        if (messageSeen < recoverCount)
                        {
                            session.Recover();
                            messageSeen++;
                        }
                        else
                        {
                            messageSeen = 0;
                            expectedIndex++;

                            // Have the peer expect the accept the disposition (1-based, hence pre-incremented).
                            testPeer.ExpectDisposition(settled: true,
                                stateMatcher: state => replacedert.AreEqual(state.Descriptor.Code, MessageSupport.ACCEPTED_INSTANCE.Descriptor.Code
                                ));

                            message.Acknowledge();

                            if (expectedIndex == messageCount)
                            {
                                complete = true;
                                latch.Set();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        complete = true;
                        asyncError = e;
                        latch.Set();
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromSeconds(15)), "Messages not received within given timeout.");
                replacedert.IsNull(asyncError, "Unexpected exception");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                await connection.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : ConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestRecoverOrderingWithAsyncConsumer()
        {
            ManualResetEvent latch = new ManualResetEvent(false);
            Exception asyncError = null;

            int recoverCount = 5;
            int messageCount = 8;
            int testPayloadLength = 255;
            string payload = Encoding.UTF8.GetString(new byte[testPayloadLength]);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                IConnection connection = EstablishConnection(testPeer);
                connection.Start();

                testPeer.ExpectBegin();

                ISession session = connection.CreateSession(AcknowledgementMode.ClientAcknowledge);
                IQueue destination = session.GetQueue("myQueue");
                connection.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(
                    message: new Amqp.Message() { BodySection = new AmqpValue() { Value = payload } },
                    count: messageCount,
                    drain: false,
                    nextIncomingId: 1,
                    addMessageNumberProperty: true,
                    sendDrainFlowResponse: false,
                    sendSettled: false,
                    creditMatcher: credit => replacedert.Greater(credit, messageCount)
                );

                IMessageConsumer consumer = session.CreateConsumer(destination);

                bool complete = false;
                int messageSeen = 0;
                int expectedIndex = 0;
                consumer.Listener += message =>
                {
                    if (complete)
                    {
                        return;
                    }

                    try
                    {
                        int actualIndex = message.Properties.GetInt(TestAmqpPeer.MESSAGE_NUMBER);
                        replacedert.AreEqual(expectedIndex, actualIndex, "Received Message Out Of Order");

                        // don't ack the message until we receive it X times
                        if (messageSeen < recoverCount)
                        {
                            session.Recover();
                            messageSeen++;
                        }
                        else
                        {
                            messageSeen = 0;
                            expectedIndex++;

                            // Have the peer expect the accept the disposition (1-based, hence pre-incremented).
                            testPeer.ExpectDisposition(settled: true,
                                stateMatcher: state => replacedert.AreEqual(state.Descriptor.Code, MessageSupport.ACCEPTED_INSTANCE.Descriptor.Code
                                ));

                            message.Acknowledge();

                            if (expectedIndex == messageCount)
                            {
                                complete = true;
                                latch.Set();
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        complete = true;
                        asyncError = e;
                        latch.Set();
                    }
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromSeconds(15)), "Messages not received within given timeout.");
                replacedert.IsNull(asyncError, "Unexpected exception");

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectClose();
                connection.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : SpeedtestHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

private int GetTcpingTime(string url, int port)
        {
            int responseTime = -1;

            try
            {
                if (!IPAddress.TryParse(url, out IPAddress ipAddress))
                {
                    IPHostEntry ipHostInfo = System.Net.Dns.GetHostEntry(url);
                    ipAddress = ipHostInfo.AddressList[0];
                }

                Stopwatch timer = new Stopwatch();
                timer.Start();

                IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
                Socket clientSocket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                IAsyncResult result = clientSocket.BeginConnect(endPoint, null, null);
                if (!result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5)))
                    throw new TimeoutException("connect timeout (5s): " + url);
                clientSocket.EndConnect(result);

                timer.Stop();
                responseTime = timer.Elapsed.Milliseconds;
                clientSocket.Close();
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);
            }
            return responseTime;
        }

19 View Source File : OVRNetwork.cs
License : MIT License
Project Creator : absurd-joy

public void Tick()
		{
			if (tcpClient == null || !tcpClient.Connected)
			{
				return;
			}

			if (readyReceiveDataEvent.WaitOne(TimeSpan.Zero))
			{
				if (tcpClient.GetStream().DataAvailable)
				{
					if (receivedBufferDataSize >= OVRNetwork.MaxBufferLength)
					{
						Debug.LogWarning("[OVRNetworkTcpClient] receive buffer overflow. It should not happen since we have the constraint on message size");
						Disconnect();
						return;
					}

					readyReceiveDataEvent.Reset();
					int maximumDataSize = OVRSystemPerfMetrics.MaxBufferLength - receivedBufferDataSize;

					tcpClient.GetStream().BeginRead(receivedBuffers[receivedBufferIndex], receivedBufferDataSize, maximumDataSize, new AsyncCallback(OnReadDataCallback), tcpClient.GetStream());
				}
			}
		}

19 View Source File : WebExtensions.cs
License : MIT License
Project Creator : aljazsim

public static void ExecuteUdpRequest(this IPEndPoint endpoint, byte[] bytes)
        {
            endpoint.CannotBeNull();
            bytes.CannotBeNullOrEmpty();

            int bufferSize = 4096;
            TimeSpan sendTimeout = TimeSpan.FromSeconds(5);
            TimeSpan receiveTimeout = TimeSpan.FromSeconds(5);
            IAsyncResult asyncResult;
            int count;

            // execute request
            using (UdpClient udp = new UdpClient())
            {
                udp.Client.SendTimeout = (int)sendTimeout.TotalMilliseconds;
                udp.Client.SendBufferSize = bytes.Length;
                udp.Client.ReceiveTimeout = (int)receiveTimeout.TotalMilliseconds;
                udp.Client.ReceiveBufferSize = bufferSize;
                udp.Connect(endpoint);

                asyncResult = udp.BeginSend(bytes, bytes.Length, null, null);

                if (asyncResult.AsyncWaitHandle.WaitOne(receiveTimeout))
                {
                    // stop reading
                    count = udp.EndSend(asyncResult);

                    if (count == bytes.Length)
                    {
                        // ok
                    }
                }
                else
                {
                    // timeout
                }

                udp.Close();
            }
        }

19 View Source File : NMSConsumerIntegrationTest.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public void TestSessionCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = EstablishNMSContext(testPeer);
                context.Start();

                testPeer.ExpectBegin();

                IQueue destination = context.GetQueue("myQueue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                
                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                context.Close();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 View Source File : NMSConsumerIntegrationTestAsync.cs
License : Apache License 2.0
Project Creator : apache

[Test, Timeout(20_000)]
        public async Task TestConsumerCloseWaitsForAsyncDeliveryToComplete()
        {
            ManualResetEvent latch = new ManualResetEvent(false);

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                var context = await EstablishNMSContextAsync(testPeer);
                await context.StartAsync();

                testPeer.ExpectBegin();

                IQueue destination = await context.GetQueueAsync("myQueue");
                await context.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlowRespondWithTransfer(message: CreateMessageWithContent(), count: 1);

                var consumer = await context.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                consumer.Listener += _ =>
                {
                    latch.Set();
                    Task.Delay(TimeSpan.FromMilliseconds(100)).GetAwaiter().GetResult();
                };

                replacedert.True(latch.WaitOne(TimeSpan.FromMilliseconds(3000)), "Messages not received within given timeout.");

                testPeer.ExpectDetach(expectClosed: true, sendResponse: true, replyClosed: true);
                await consumer.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);

                testPeer.ExpectEnd();
                testPeer.ExpectClose();
                await context.CloseAsync();

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

See More Examples