System.Threading.WaitHandle.WaitOne(int)

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

902 Examples 7

19 Source : RtmpServer.cs
with MIT License
from a1q123456

public Task StartAsync(CancellationToken ct = default)
        {
            if (Started)
            {
                throw new InvalidOperationException("already started");
            }
            _webSocketServer?.Start(c =>
            {
                var session = new WebSocketSession(c, _webSocketOptions);
                c.OnOpen = session.HandleOpen;
                c.OnClose = session.HandleClose;
                c.OnMessage = session.HandleMessage;
            });

            if (_webSocketServer != null)
            {
                CancellationTokenRegistration reg = default;
                reg = ct.Register(() =>
                {
                    reg.Dispose();
                    _webSocketServer.Dispose();
                    _webSocketServer = new WebSocketServer(_webSocketOptions.BindEndPoint.ToString());
                });
            }
            Started = true;
            var ret = new TaskCompletionSource<int>();
            var t = new Thread(o =>
            {
                try
                {
                    while (!ct.IsCancellationRequested)
                    {
                        try
                        {
                            _allDone.Reset();
                            _listener.BeginAccept(new AsyncCallback(ar =>
                            {
                                AcceptCallback(ar, ct);
                            }), _listener);
                            while (!_allDone.WaitOne(1))
                            {
                                ct.ThrowIfCancellationRequested();
                            }
                        }
                        catch (OperationCanceledException)
                        {
                            throw;
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.ToString());
                        }
                    }
                }
                catch (OperationCanceledException) { }
                finally
                {
                    ret.SetResult(1);
                }
            });

            t.Start();
            return ret.Task;
        }

19 Source : OVRNetwork.cs
with MIT License
from absurd-joy

public void Disconnect()
		{
			if (tcpClient != null)
			{
				if (!readyReceiveDataEvent.WaitOne(5))
				{
					Debug.LogWarning("[OVRNetworkTcpClient] readyReceiveDataEvent not signaled. data receiving timeout?");
				}

				Debug.Log("[OVRNetworkTcpClient] close tcpClient");
				try
				{
					tcpClient.GetStream().Close();
					tcpClient.Close();
				}
				catch (Exception e)
				{
					Debug.LogWarning("[OVRNetworkTcpClient] " + e.Message);
				}
				tcpClient = null;

				if (connectionStateChangedCallback != null)
				{
					connectionStateChangedCallback();
				}
			}
			else
			{
				Debug.LogWarning("[OVRNetworkTcpClient] not connected");
			}
		}

19 Source : AudioDeviceHandler.cs
with MIT License
from ABTSoftware

private void ProcessData()
        {
            while (!_token.IsCancellationRequested)
            {
                if (_processEvt.WaitOne(100))
                {
                    lock (_input)
                    {
                        Array.Copy(_input, _inputBack, _input.Length);
                    }
                    DataReceived?.Invoke(this, EventArgs.Empty);
                }
            }
        }

19 Source : MutexExtensions.cs
with MIT License
from Adoxio

public static void Lock(string key, int millisecondsTimeout, Action<Mutex> action)
		{
			var processSpecificKey = GetProcessSpecificKey(key);

			using (var mutex = new Mutex(false, processSpecificKey))
			{
				try
				{
					if (!mutex.WaitOne(millisecondsTimeout))
					{
						throw new TimeoutException("A timeout occurred while waiting on the named mutex '{0}'.".FormatWith(key));
					}

					action(mutex);
				}
				finally
				{
					mutex.ReleaseMutex();
				}
			}
		}

19 Source : UdpSocket.cs
with Apache License 2.0
from advancer68

void process_kcpio_queue(object state)
        {
            while (Connected)
            {
                try
                {
                    //send process
                    snd_queue.DequeueAll(it =>
                    {
                        SendPacket(it);
                        //mKcp.Send(it);
                    });
                    Stopwatch t = new Stopwatch();
                    t.Start();
                    mKcp.Flush((int)kcpUtil.nowTotalMilliseconds);
                    rcv_queue.DequeueAll(it =>
                    {
                        mKcp.Input(it);
                    });
                    rcvCache.Clear();
                    //rcvCache.Capacity(peekSize);
                    while (true)
                    {
                        int peekSize = mKcp.PeekSize();
                        if (peekSize > 0)
                        {
                            int rcvSize = mKcp.Receive(rcvCache);
                            if (rcvSize > 0)
                            {
                                //packer.Recv(rcvCache);
                                Unpack(rcvCache);
                            }
                            else { break; }
                        }
                        else { break; }
                    }
                    t.Stop();
                    if (t.ElapsedMilliseconds > 5)
                    {
                        Console.WriteLine(string.Format("used time:{0}", t.ElapsedMilliseconds));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
                finally
                {
                    //Console.WriteLine("thread run error");
                }
                if (kcpThreadNotify.WaitOne(5))
                {
                    Thread.Sleep(2);
                }
            }
        }

19 Source : Model.cs
with MIT License
from advancedmonitoring

public static void OnClose()
        {
            if (!TextChangedEvent.WaitOne(0))
                TextChangedEvent.Set();
        }

19 Source : UIPerformWorkWindow.xaml.cs
with MIT License
from advancedmonitoring

private void timer_Tick(object sender, EventArgs e)
        {
            _lIndex = (_lIndex + 1) % 8;
            _lines[_lIndex].Stroke = _brush1;
            _lines[(_lIndex + 7) % 8].Stroke = _brush2;
            _lines[(_lIndex + 6) % 8].Stroke = _brush3;
            if (_percentage != Percentage)
            {
                lblPercentage.Text = string.Format(_percentFormat, Percentage);
                _percentage = Percentage;
            }
            if (AbortEvent.WaitOne(0))
                Close();
        }

19 Source : Model.cs
with MIT License
from advancedmonitoring

private static void TextChangedSpinnerFunc()
        {
            while (true)
            {
                Thread.Sleep(300);
                var head = "User/Group/SID";
                if (_textChangedThread != null && _textChangedThread.IsAlive)
                {
                    _textChangedIndex = (_textChangedIndex + 1) % 4;
                    head = "[" + "|/-\\"[_textChangedIndex] + "] " + head;
                }
                MW.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                    new Action<string>((x) => MW.grpUGS.Header = x), head);
                if (TextChangedEvent.WaitOne(0))
                {
                    MW.Dispatcher.BeginInvoke(DispatcherPriority.Background,
                        new Action(() => MW.grpUGS.Header = "User/Group/SID"));
                    Thread.CurrentThread.Abort();
                    return;
                }
            }
        }

19 Source : Model.cs
with MIT License
from advancedmonitoring

private static void TextChangedFunc(object o)
        {
            var data = (string)o;
            var lines = data.Split('\r', '\n');
            var allSIDs = new List<string>();
            var allRights = new List<string>();
            var prevSids = 0;
            var prevRights = 0;
            foreach (var line in lines)
            {
                if (!string.IsNullOrWhiteSpace(line))
                {
                    var sd = new SecurityDescriptor(line.Trim());
                    if (!sd.IsOk)
                        continue;

                    var lSIDs = sd.GetAllSIDs();
                    foreach (var sid in lSIDs)
                        if (!allSIDs.Contains(sid))
                            allSIDs.Add(sid);

                    var lRights = sd.GetAllRights();
                    foreach (var right in lRights)
                        if (!allRights.Contains(right))
                            allRights.Add(right);

                    if (allSIDs.Count != prevSids)
                    {
                        prevSids = allSIDs.Count;
                        var sortedSIDs = allSIDs.OrderBy(q => q[1] == '-' ? "ZZ" + q : q).ToList();
                        MW.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action<List<string>>((x) =>
                        {
                            MW.SIDList.Clear();
                            foreach (var sid in x)
                                MW.SIDList.Add(new BoolStringClreplaced(SecurityDescriptor.SIDToLong(sid, MW.IsTranslateSID), sid));
                        }), sortedSIDs);
                    }

                    if (allRights.Count != prevRights)
                    {
                        prevRights = allRights.Count;
                        MW.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() =>
                        {
                            var newRightsList = new ObservableCollection<BoolStringClreplaced>();
                            foreach (var element in MW.RightsList)
                            {
                                if (allRights.Contains(element.Tag))
                                    element.TextBrush = new SolidColorBrush(Color.FromRgb(50, 150, 255));
                                newRightsList.Add(element);
                            }
                            MW.RightsList.Clear();
                            foreach (var element in newRightsList)
                                MW.RightsList.Add(element);
                        }));
                    }
                }
                if (TextChangedEvent.WaitOne(0))
                {
                    if (_textChangedSpinnerThread != null && _textChangedSpinnerThread.IsAlive)
                        _textChangedSpinnerThread.Join();
                    Thread.CurrentThread.Abort();
                    return;
                }
            }
            
            TextChangedEvent.Set();
            if (_textChangedSpinnerThread != null && _textChangedSpinnerThread.IsAlive)
                _textChangedSpinnerThread.Join();
            Thread.CurrentThread.Abort();
        }

19 Source : MulitToOneQueue.cs
with Mozilla Public License 2.0
from agebullhu

public bool StartProcess(out T t, int waitMs)
        {
            lock (this)
            {
                if (_disposedValue)
                {
                    t = default(T);
                    return false;
                }
                if (Doing.Count > 0)//之前存在失败
                {
                    lock (Doing)
                        t = Doing.Peek();
                    return true;
                }
                if (!_semapreplaced.WaitOne(waitMs))
                {
                    t = default(T);
                    return false;
                }
                t = Queue.Dequeue();
                Doing.Enqueue(t);
            }
            return true;
        }

19 Source : SchemeChangeSubscriberTest.cs
with Apache License 2.0
from Aguafrommars

[Fact]
        public async Task Subscribe_should_subcribe_to_hub_events()
        {
            var waitHandle = new ManualResetEvent(false);

            var configuration = new Dictionary<string, string>
            {
                ["ConnectionStrings:DefaultConnection"] = Guid.NewGuid().ToString(),
                ["ApiAuthentication:Authority"] = "http://localhost",
                ["SignalR:HubUrl"] = "http://localhost/providerhub",
                ["SignalR:UseMessagePack"] = "false",
                ["Seed"] = "true"
            };

            TestServer server = null;
            server = TestUtils.CreateTestServer(services =>
            {
                services.RemoveAll<HubHttpMessageHandlerAccessor>();
                services.AddTransient(p => new HubHttpMessageHandlerAccessor { Handler = new MockHttpMessageHandler(waitHandle, server.CreateHandler()) });
                services.RemoveAll<HttpClient>();
                services.AddTransient(p => server.CreateClient());
                services.RemoveAll<HttpClientHandler>();
                services.AddTransient<HttpClientHandler>(p => new MockHttpClientHandler(p.GetRequiredService<HttpClient>()));
            }, configuration, (endpoints, isProxy) =>
            {
                endpoints.MapRazorPages();
                endpoints.MapDefaultControllerRoute();
                if (!isProxy)
                {
                    endpoints.MapHub<ProviderHub>("/providerhub");
                }
            });

            server.CreateWebSocketClient();

            var provider = server.Host.Services;
            var store = provider.GetRequiredService<IAdminStore<ExternalProvider>>();
            var serializer = provider.GetRequiredService<IAuthenticationSchemeOptionsSerializer>();

            var manager = new NoPersistentDynamicManager<SchemeDefinition>(new Mock<IAuthenticationSchemeProvider>().Object, new OptionsMonitorCacheWrapperFactory(new Mock<IServiceProvider>().Object), Array.Empty<Type>());
            var wrapper1 = new KeyManagerWrapper<Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.IAuthenticatedEncryptorDescriptor>(new Mock<IKeyManager>().Object, new Mock<IDefaultKeyResolver>().Object, new Mock<IProviderClient>().Object);
            var wrapper2 = new KeyManagerWrapper<IdenreplacedyServer.KeysRotation.RsaEncryptorDescriptor>(new Mock<IKeyManager>().Object, new Mock<IDefaultKeyResolver>().Object, new Mock<IProviderClient>().Object);
            var hubConnectionFactory = new HubConnectionFactory(provider.GetRequiredService<IConfiguration>(), provider, new NullLogger<HubConnectionFactory>());

            var connection = hubConnectionFactory.GetConnection(default);
            replacedert.NotNull(connection);
            await hubConnectionFactory.StartConnectionAsync(default);

            var subscriber = new SchemeChangeSubscriber<SchemeDefinition>(hubConnectionFactory, manager, new Mock<IDynamicProviderStore<SchemeDefinition>>().Object, wrapper1, wrapper2, new NullLogger<SchemeChangeSubscriber<SchemeDefinition>>());
            await subscriber.SubscribeAsync(default).ConfigureAwait(false);

            var extProvider = new ExternalProvider
            {
                DisplayName = "Google",
                Id = "google",
                KindName = "Google",
                SerializedHandlerType = serializer.SerializeType(typeof(GoogleHandler)),
                SerializedOptions = serializer.SerializeOptions(new GoogleOptions(), typeof(GoogleOptions))
            };

            var result = waitHandle.WaitOne(5000);

            replacedert.True(result);

            await store.CreateAsync(extProvider).ConfigureAwait(false);
            await store.UpdateAsync(extProvider).ConfigureAwait(false);
            await store.DeleteAsync("google").ConfigureAwait(false);

            var providerClient = provider.GetRequiredService<IProviderClient>();

            await providerClient.KeyRevokedAsync(nameof(IAuthenticatedEncryptorDescriptor), Guid.NewGuid().ToString()).ConfigureAwait(false);
            await providerClient.KeyRevokedAsync(nameof(RsaEncryptorDescriptor), Guid.NewGuid().ToString()).ConfigureAwait(false);

            provider.GetRequiredService<IConfiguration>()["SignalR:HubUrl"] = null;

            await store.CreateAsync(extProvider).ConfigureAwait(false);
            await store.UpdateAsync(extProvider).ConfigureAwait(false);
            await store.DeleteAsync("google").ConfigureAwait(false);

            await providerClient.KeyRevokedAsync("test", "test").ConfigureAwait(false);
        }

19 Source : SharedMemory.cs
with GNU General Public License v3.0
from aiportal

private void MutexInvoke(Action action, int timeout = Timeout.Infinite)
		{
			if (_mutex.WaitOne(timeout))
			{
				try
				{
					action();
				}
				catch (Exception ex) { TraceLog.WriteException(ex); throw; }
				finally
				{
					_mutex.ReleaseMutex();
				}
			}
		}

19 Source : App.cs
with MIT License
from alexanderdna

public void Mine()
        {
            if (WalletLoggedIn is false)
                throw new WalletNotAvailableException();

            if (chainMutex.WaitOne(millisecondsTimeout: 3000) is false)
            {
                Logger.Log(LogLevel.Warning, "Cannot start mining: chainMutex is held too long.");
                throw new ChainMutexLockedException();
            }
            long remainingMs = ChainManager.GetRemainingMsToNewBlock();
            chainMutex.ReleaseMutex();

            if (remainingMs > 0)
                throw new NotValidTimeForNewBlockException(remainingMs);

            Task.Run(() =>
            {
                IsMining = true;

                if (chainMutex.WaitOne(millisecondsTimeout: 3000) is false)
                {
                    Logger.Log(LogLevel.Warning, "Cannot start mining: chainMutex is held too long.");
                    LastMiningSuccessful = false;
                    return;
                }

                var mining = ChainManager.PrepareMining(_walletAddress, nonceRange: 100_000);
                chainMutex.ReleaseMutex();

                var token = CancellationTokenSource.Token;
                while (token.IsCancellationRequested is false)
                {
                    bool isFound = mining.Attempt();

                    double hashMs = Pow.LastMiningMilliseconds;
                    MiningHashrate = 1000.0 / hashMs;

                    if (isFound || mining.IsExhausted)
                        break;
                }

                var foundBlock = mining.Block;
                if (foundBlock is not null)
                {
                    if (chainMutex.WaitOne(millisecondsTimeout: 3000) is false)
                    {
                        Logger.Log(LogLevel.Warning, "Cannot finish mining: chainMutex is held too long.");
                        LastMiningSuccessful = false;
                        return;
                    }

                    var isAdded = ChainManager.FinishMining();
                    chainMutex.ReleaseMutex();

                    if (isAdded is true)
                        Daemon.BroadcastLatestBlock();
                    else
                        foundBlock = null;
                }
                else
                {
                    ChainManager.CancelMining();
                }

                IsMining = false;
                LastMiningSuccessful = foundBlock is not null;
            }

19 Source : VideoAnalyzer.cs
with MIT License
from AlturosDestinations

private async Task<replacedyzeResult> GetVideoInfoAsync(MediaInput mediaInput, CancellationToken cancellationToken = default)
        {
            if (!File.Exists(this._ffprobePath))
            {
                return new replacedyzeResult { Successful = false, ErrorMessage = $"ffprobe could not be found {this._ffprobePath}" };
            }

            var startInfo = new ProcessStartInfo
            {
                FileName = this._ffprobePath,
                RedirectStandardOutput = true,
                UseShellExecute = false,
                CreateNoWindow = true,
            };

            if (mediaInput.FileContent != null)
            {
                startInfo.RedirectStandardInput = true;
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams -";
            }
            else
            {
                startInfo.Arguments = $"-v quiet -print_format json -show_format -show_streams \"{mediaInput.FilePath}\"";
            }

            using (var outputWaitHandle = new AutoResetEvent(false))
            {
                var json = new StringBuilder();

                var dataReceived = new DataReceivedEventHandler((sender, e) =>
                {
                    if (e.Data == null)
                    {
                        outputWaitHandle.Set();
                        return;
                    }

                    json.AppendLine(e.Data);
                });

                this._process = new Process();

                try
                {
                    this._process.StartInfo = startInfo;
                    this._process.OutputDataReceived += dataReceived;

                    if (!this._process.Start())
                    {
                        return new replacedyzeResult { ErrorMessage = "Cannot start ffprobe" };
                    }

                    this._process.BeginOutputReadLine();

                    if (mediaInput.FileContent != null)
                    {
                        using (var ffprobeIn = this._process.StandardInput.BaseStream)
                        {
                            var packageSize = 100000;
                            for (var i = 0; i < mediaInput.FileContent.Length; i += packageSize)
                            {
                                var package = mediaInput.FileContent.Skip(i).Take(packageSize).ToArray();
                                await ffprobeIn.WriteAsync(package, 0, package.Length, cancellationToken);
                            }
                            await ffprobeIn.FlushAsync(cancellationToken);
                            ffprobeIn.Close();
                        }
                    }

                    if (!this._process.WaitForExit(this._timeout) || !outputWaitHandle.WaitOne(this._timeout))
                    {
                        return new replacedyzeResult { ErrorMessage = $"Timeout reached {this._timeout} (ms)" };
                    }

                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (IOException)
                {
                    var videoInfo = JsonConvert.DeserializeObject<VideoInfoResult>(json.ToString(), this._jsonSerializerSettings);
                    if (videoInfo.Format == null && videoInfo.Streams == null)
                    {
                        return new replacedyzeResult { Successful = false, ErrorMessage = "No feedback from ffprobe (IOException)" };
                    }

                    return new replacedyzeResult { Successful = true, VideoInfo = videoInfo };
                }
                catch (Exception exception)
                {
                    return new replacedyzeResult { Successful = false, ErrorMessage = exception.ToString() };
                }
                finally
                {
                    this._process.OutputDataReceived -= dataReceived;
                    this._process?.Dispose();
                }
            }
        }

19 Source : WorkerThreadPool.cs
with MIT License
from AmplifyCreations

private static void AsyncUpdateThread( object obj )
	{
	#if !NETFX_CORE && !UNITY_WEBGL
		KeyValuePair<object, int> pair = ( KeyValuePair<object, int> ) obj;
		WorkerThreadPool pool = ( WorkerThreadPool ) pair.Key;
		int id = ( int ) pair.Value;

		while ( true )
		{
			try
			{
				pool.m_threadPoolContinueSignals[ id ].WaitOne();

				if ( pool.m_threadPoolTerminateSignal.WaitOne( 0 ) )
					break;

				while ( true )
				{
					AmplifyMotion.MotionState state = null;

					lock ( pool.m_threadStateQueueLocks[ id ] )
					{
						if ( pool.m_threadStateQueues[ id ].Count > 0 )
							state = pool.m_threadStateQueues[ id ].Dequeue();
					}

					if ( state != null )
						state.AsyncUpdate();
					else
						break;
				}
			}
			catch ( System.Exception e )
			{
				if ( e.GetType() != typeof( ThreadAbortException ) )
					Debug.LogWarning( e );
			}
		}
	#endif
	}

19 Source : ProfiledProcessManager.cs
with GNU General Public License v3.0
from AndreiFedarets

public void Close()
        {
            if (_process != null && !_process.HasExited)
            {
                try
                {
                    if (_process.MainWindowHandle != IntPtr.Zero)
                    {
                        Action action = () => _process.CloseMainWindow();
                        IAsyncResult asyncResult = action.BeginInvoke(null, null);
                        asyncResult.AsyncWaitHandle.WaitOne(5000);
                    }
                }
                catch (Exception exception)
                {
                    LoggingProvider.Current.Log(TraceEventType.Information, exception);
                }
                if (!_process.HasExited)
                {
                    _process.Kill();
                }
            }
        }

19 Source : ProfilingTargetController.cs
with GNU General Public License v3.0
from AndreiFedarets

public void Stop()
        {
            if (_serviceProcess != null)
            {
                _serviceProcess.Refresh();
                if (!_serviceProcess.HasExited)
                {
                    Action action = () => _service.Stop();
                    IAsyncResult asyncResult = action.BeginInvoke(null, null);
                    asyncResult.AsyncWaitHandle.WaitOne(ServiceProcessClosingTimeout);
                    if (IsActive)
                    {
                        _serviceProcess.Kill();
                    }   
                }
            }
            if (_isServiceInitialyRunning)
            {
                _service.Start();
            }
        }

19 Source : HttpListenerRequest.cs
with MIT License
from andruzzzhka

internal bool FlushInput ()
    {
      var input = InputStream;
      if (input == Stream.Null)
        return true;

      var len = 2048;
      if (_contentLength > 0 && _contentLength < len)
        len = (int) _contentLength;

      var buff = new byte[len];

      while (true) {
        try {
          var ares = input.BeginRead (buff, 0, len, null, null);
          if (!ares.IsCompleted) {
            var timeout = 100;
            if (!ares.AsyncWaitHandle.WaitOne (timeout))
              return false;
          }

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

19 Source : ConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestRemotelyCloseConsumer()
        {
            Mock<INmsConnectionListener> mockConnectionListener = new Mock<INmsConnectionListener>();
            string errorMessage = "buba";

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent consumerClosed = new ManualResetEvent(false);
                ManualResetEvent exceptionFired = new ManualResetEvent(false);

                mockConnectionListener
                    .Setup(listener => listener.OnConsumerClosed(It.IsAny<IMessageConsumer>(), It.IsAny<Exception>()))
                    .Callback(() => consumerClosed.Set());

                NmsConnection connection = (NmsConnection) EstablishConnection(testPeer);
                connection.AddConnectionListener(mockConnectionListener.Object);
                connection.ExceptionListener += exception => { exceptionFired.Set(); };

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

                // Create a consumer, then remotely end it afterwards.
                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RemotelyDetachLastOpenedLinkOnLastOpenedSession(expectDetachResponse: true, closed: true, errorType: AmqpError.RESOURCE_DELETED, errorMessage: errorMessage, delayBeforeSend: 400);

                IQueue queue = session.GetQueue("myQueue");
                IMessageConsumer consumer = session.CreateConsumer(queue);

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

                replacedert.True(consumerClosed.WaitOne(2000), "Consumer closed callback didn't trigger");
                replacedert.False(exceptionFired.WaitOne(20), "Exception listener shouldn't fire with no MessageListener");

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

19 Source : ConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestRemotelyCloseConsumerWithMessageListenerFiresExceptionListener()
        {
            Mock<INmsConnectionListener> mockConnectionListener = new Mock<INmsConnectionListener>();
            string errorMessage = "buba";

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent consumerClosed = new ManualResetEvent(false);
                ManualResetEvent exceptionFired = new ManualResetEvent(false);

                mockConnectionListener
                    .Setup(listener => listener.OnConsumerClosed(It.IsAny<IMessageConsumer>(), It.IsAny<Exception>()))
                    .Callback(() => consumerClosed.Set());

                NmsConnection connection = (NmsConnection) EstablishConnection(testPeer);
                connection.AddConnectionListener(mockConnectionListener.Object);
                connection.ExceptionListener += exception => { exceptionFired.Set(); };

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

                // Create a consumer, then remotely end it afterwards.
                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RemotelyDetachLastOpenedLinkOnLastOpenedSession(expectDetachResponse: true, closed: true, errorType: AmqpError.RESOURCE_DELETED, errorMessage: errorMessage, 10);

                IQueue queue = session.GetQueue("myQueue");
                IMessageConsumer consumer = session.CreateConsumer(queue);

                consumer.Listener += message => { };

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

                replacedert.True(consumerClosed.WaitOne(2000), "Consumer closed callback didn't trigger");
                replacedert.True(exceptionFired.WaitOne(2000), "Exception listener should have fired with a MessageListener");

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

19 Source : ConsumerIntegrationTest.cs
with Apache License 2.0
from apache

private void DoTestConsumerReceiveThrowsIfConnectionLost(bool useTimeout)
        {
            ManualResetEvent consumerReady = new ManualResetEvent(false);

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

                testPeer.ExpectBegin();

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

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RunAfterLastHandler(() => { consumerReady.WaitOne(2000); });
                testPeer.DropAfterLastMatcher(delay: 10);

                IMessageConsumer consumer = session.CreateConsumer(queue);
                consumerReady.Set();

                try
                {
                    if (useTimeout)
                    {
                        consumer.Receive(TimeSpan.FromMilliseconds(10_0000));
                    }
                    else
                    {
                        consumer.Receive();
                    }


                    replacedert.Fail("An exception should have been thrown");
                }
                catch (NMSException)
                {
                    // Expected
                }

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }

19 Source : ConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestMessageListenerCallsConnectionCloseThrowsIllegalStateException()
        {
            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(), 1);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(4000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : ConsumerIntegrationTest.cs
with Apache License 2.0
from 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 Source : ConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestMessageListenerCallsSessionCloseThrowsIllegalStateException()
        {
            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(), 1);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : ConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestRemotelyCloseConsumer()
        {
            Mock<INmsConnectionListener> mockConnectionListener = new Mock<INmsConnectionListener>();
            string errorMessage = "buba";

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent consumerClosed = new ManualResetEvent(false);
                ManualResetEvent exceptionFired = new ManualResetEvent(false);

                mockConnectionListener
                    .Setup(listener => listener.OnConsumerClosed(It.IsAny<IMessageConsumer>(), It.IsAny<Exception>()))
                    .Callback(() => consumerClosed.Set());

                NmsConnection connection = (NmsConnection) await EstablishConnectionAsync(testPeer);
                connection.AddConnectionListener(mockConnectionListener.Object);
                connection.ExceptionListener += exception => { exceptionFired.Set(); };

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

                // Create a consumer, then remotely end it afterwards.
                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RemotelyDetachLastOpenedLinkOnLastOpenedSession(expectDetachResponse: true, closed: true, errorType: AmqpError.RESOURCE_DELETED, errorMessage: errorMessage, delayBeforeSend: 400);

                IQueue queue = await session.GetQueueAsync("myQueue");
                IMessageConsumer consumer = await session.CreateConsumerAsync(queue);

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

                replacedert.True(consumerClosed.WaitOne(2000), "Consumer closed callback didn't trigger");
                replacedert.False(exceptionFired.WaitOne(20), "Exception listener shouldn't fire with no MessageListener");

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

19 Source : ConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestRemotelyCloseConsumerWithMessageListenerFiresExceptionListener()
        {
            Mock<INmsConnectionListener> mockConnectionListener = new Mock<INmsConnectionListener>();
            string errorMessage = "buba";

            using (TestAmqpPeer testPeer = new TestAmqpPeer())
            {
                ManualResetEvent consumerClosed = new ManualResetEvent(false);
                ManualResetEvent exceptionFired = new ManualResetEvent(false);

                mockConnectionListener
                    .Setup(listener => listener.OnConsumerClosed(It.IsAny<IMessageConsumer>(), It.IsAny<Exception>()))
                    .Callback(() => consumerClosed.Set());

                NmsConnection connection = (NmsConnection) await EstablishConnectionAsync(testPeer);
                connection.AddConnectionListener(mockConnectionListener.Object);
                connection.ExceptionListener += exception => { exceptionFired.Set(); };

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

                // Create a consumer, then remotely end it afterwards.
                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RemotelyDetachLastOpenedLinkOnLastOpenedSession(expectDetachResponse: true, closed: true, errorType: AmqpError.RESOURCE_DELETED, errorMessage: errorMessage, 10);

                IQueue queue = await session.GetQueueAsync("myQueue");
                IMessageConsumer consumer = await session.CreateConsumerAsync(queue);

                consumer.Listener += message => { };

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

                replacedert.True(consumerClosed.WaitOne(2000), "Consumer closed callback didn't trigger");
                replacedert.True(exceptionFired.WaitOne(2000), "Exception listener should have fired with a MessageListener");

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

19 Source : ConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

private async Task DoTestConsumerReceiveThrowsIfConnectionLost(bool useTimeout)
        {
            ManualResetEvent consumerReady = new ManualResetEvent(false);

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

                testPeer.ExpectBegin();

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

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RunAfterLastHandler(() => { consumerReady.WaitOne(2000); });
                testPeer.DropAfterLastMatcher(delay: 10);

                IMessageConsumer consumer = await session.CreateConsumerAsync(queue);
                consumerReady.Set();

                try
                {
                    if (useTimeout)
                    {
                        await consumer.ReceiveAsync(TimeSpan.FromMilliseconds(10_0000));
                    }
                    else
                    {
                        await consumer.ReceiveAsync();
                    }


                    replacedert.Fail("An exception should have been thrown");
                }
                catch (NMSException)
                {
                    // Expected
                }

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }

19 Source : ConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestMessageListenerCallsConnectionCloseThrowsIllegalStateException()
        {
            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(), 1);

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(4000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : ConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestMessageListenerCallsConnectionStopThrowsIllegalStateException()
        {
            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(), 1);

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                ManualResetEvent latch = new ManualResetEvent(false);
                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        connection.Stop();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : ConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestMessageListenerCallsSessionCloseThrowsIllegalStateException()
        {
            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(), 1);

                IMessageConsumer consumer = await session.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : ConsumerIntegrationTestAsync.cs
with Apache License 2.0
from 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 Source : NMSConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

private async Task DoTestConsumerReceiveThrowsIfConnectionLost(bool useTimeout)
        {
            ManualResetEvent consumerReady = new ManualResetEvent(false);

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

                testPeer.ExpectBegin();

                IQueue queue = await context.GetQueueAsync("queue");
                await context.StartAsync();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RunAfterLastHandler(() => { consumerReady.WaitOne(2000); });
                testPeer.DropAfterLastMatcher(delay: 10);

                var consumer = await context.CreateConsumerAsync(queue);
                consumerReady.Set();

                try
                {
                    if (useTimeout)
                    {
                        await consumer.ReceiveAsync(TimeSpan.FromMilliseconds(10_0000));
                    }
                    else
                    {
                        await consumer.ReceiveAsync();
                    }


                    replacedert.Fail("An exception should have been thrown");
                }
                catch (NMSException)
                {
                    // Expected
                }

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }

19 Source : NMSConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestMessageListenerCallsConnectionCloseThrowsIllegalStateException()
        {
            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(), 1);

                var consumer = await context.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(4000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : NMSConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestMessageListenerCallsConnectionStopThrowsIllegalStateException()
        {
            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(), 1);

                var consumer = await context.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                ManualResetEvent latch = new ManualResetEvent(false);
                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        context.Stop();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : NMSConsumerIntegrationTestAsync.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public async Task TestMessageListenerCallsSessionCloseThrowsIllegalStateException()
        {
            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(), 1);

                var consumer = await context.CreateConsumerAsync(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : NMSConsumerIntegrationTestAsync.cs
with Apache License 2.0
from 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 Source : ConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestMessageListenerCallsConnectionStopThrowsIllegalStateException()
        {
            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(), 1);

                IMessageConsumer consumer = session.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                ManualResetEvent latch = new ManualResetEvent(false);
                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        connection.Stop();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : NMSConsumerIntegrationTest.cs
with Apache License 2.0
from apache

private void DoTestConsumerReceiveThrowsIfConnectionLost(bool useTimeout)
        {
            ManualResetEvent consumerReady = new ManualResetEvent(false);

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

                testPeer.ExpectBegin();

                IQueue queue = context.GetQueue("queue");
                context.Start();

                testPeer.ExpectReceiverAttach();
                testPeer.ExpectLinkFlow();
                testPeer.RunAfterLastHandler(() => { consumerReady.WaitOne(2000); });
                testPeer.DropAfterLastMatcher(delay: 10);

                var consumer = context.CreateConsumer(queue);
                consumerReady.Set();

                try
                {
                    if (useTimeout)
                    {
                        consumer.Receive(TimeSpan.FromMilliseconds(10_0000));
                    }
                    else
                    {
                        consumer.Receive();
                    }


                    replacedert.Fail("An exception should have been thrown");
                }
                catch (NMSException)
                {
                    // Expected
                }

                testPeer.WaitForAllMatchersToComplete(1000);
            }
        }

19 Source : NMSConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestMessageListenerCallsConnectionCloseThrowsIllegalStateException()
        {
            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(), 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(4000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : NMSConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestMessageListenerCallsConnectionStopThrowsIllegalStateException()
        {
            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(), 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

                ManualResetEvent latch = new ManualResetEvent(false);
                Exception exception = null;
                consumer.Listener += message =>
                {
                    try
                    {
                        context.Stop();
                    }
                    catch (Exception e)
                    {
                        exception = e;
                    }

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : NMSConsumerIntegrationTest.cs
with Apache License 2.0
from apache

[Test, Timeout(20_000)]
        public void TestMessageListenerCallsSessionCloseThrowsIllegalStateException()
        {
            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(), 1);

                var consumer = context.CreateConsumer(destination);

                testPeer.ExpectDispositionThatIsAcceptedAndSettled();

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

                    latch.Set();
                };

                replacedert.True(latch.WaitOne(3000), "Messages not received within given timeout.");
                replacedert.IsNotNull(exception);
                replacedert.IsInstanceOf<IllegalStateException>(exception);

                testPeer.WaitForAllMatchersToComplete(2000);

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

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

                testPeer.WaitForAllMatchersToComplete(2000);
            }
        }

19 Source : NMSConsumerIntegrationTest.cs
with Apache License 2.0
from 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 Source : MainWindow.axaml.cs
with GNU Affero General Public License v3.0
from arklumpus

private void UIUpdater()
        {
            Grid cacheFillGrid = this.FindControl<Grid>("CacheFillGrid");
            Canvas cacheFillCanvas = this.FindControl<Canvas>("CacheFillCanvas");
            PDFRenderer renderer = this.FindControl<PDFRenderer>("MuPDFRenderer");

            Thread thr = new Thread(async () =>
            {
                //Keep running until the window is closed.
                while (!ClosedHandle.WaitOne(0))
                {
                    if (Context != null)
                    {
                        long currentSize = Context.StoreSize;
                        long maxSize = Context.StoreMaxSize;

                        double perc = (double)currentSize / (double)maxSize;

                        await Dispatcher.UIThread.InvokeAsync(() =>
                        {
                            cacheFillGrid.ColumnDefinitions[0] = new ColumnDefinition(perc, GridUnitType.Star);
                            cacheFillGrid.ColumnDefinitions[1] = new ColumnDefinition(1 - perc, GridUnitType.Star);

                            ToolTip.SetTip(cacheFillGrid, perc.ToString("0%") + " (" + Math.Round(currentSize / 1024.0 / 1024.0).ToString("0") + "/" + Math.Round(maxSize / 1024.0 / 1024.0).ToString("0") + "MiB)");

                            if (perc <= 0.5)
                            {
                                cacheFillCanvas.Background = new SolidColorBrush(Color.FromRgb(187, 204, 51));
                            }
                            else if (perc <= 0.75)
                            {
                                cacheFillCanvas.Background = new SolidColorBrush(Color.FromRgb(238, 221, 136));
                            }
                            else
                            {
                                cacheFillCanvas.Background = new SolidColorBrush(Color.FromRgb(238, 136, 102));
                            }

                            //The update does not need to have a high priority.
                        }, DispatcherPriority.MinValue);
                    }
                    else
                    {
                        cacheFillGrid.ColumnDefinitions[0] = new ColumnDefinition(0, GridUnitType.Star);
                        cacheFillGrid.ColumnDefinitions[1] = new ColumnDefinition(1, GridUnitType.Star);
                    }

                    //We don't need to keep polling too often.
                    Thread.Sleep(2000);
                }
            });

            thr.Start();
        }

19 Source : Program.cs
with GNU Affero General Public License v3.0
from arklumpus

static void Main(string[] args)
        {
            if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("NO_COLOR")))
            {
                ConsoleWrapper.ColourEnabled = false;
            }

            Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture;

            InstanceStateData.IsUIAvailable = false;

            if (Console.IsInputRedirected)
            {
                InstanceStateData.IsInteractive = false;
            }

            Console.OutputEncoding = Encoding.UTF8;
            ConsoleWrapper.SetOutputMode(ConsoleWrapper.OutputModes.Error);

            ConsoleWrapper.WriteLine("TreeViewer v" + TreeViewer.Program.Version + " (command-line v" + Version + ")");
            ConsoleWrapper.WriteLine();

            ConsoleWrapper.Write("Loading installed modules...");

            _ = Modules.LoadInstalledModules(true, null);

            ConsoleWrapper.WriteLine(" Done.");
            ConsoleWrapper.WriteLine();

            StateData.AddPlottingModule = (module) =>
            {
                ModuleCommand.EnableModule(Modules.LoadedModulesMetadata[module.Id], -1, new Dictionary<string, object>());

                return PlotActions[^1].Item2.UpdateParameterAction;
            };

            StateData.RemovePlottingModule = (index) =>
            {
                ModuleCommand.DisableModule(PlotActions[index].Item2);
            };

            StateData.AddFurtherTransformationModule = (module) =>
            {
                ModuleCommand.EnableModule(Modules.LoadedModulesMetadata[module.Id], -1, new Dictionary<string, object>());

                return FurtherTransformations[^1].Item2.UpdateParameterAction;
            };

            StateData.RemoveFurtherTransformationModule = (index) =>
            {
                ModuleCommand.DisableModule(FurtherTransformations[index].Item2);
            };

            StateData.SetCoordinatesModule = (module) =>
            {
                ModuleCommand.EnableModule(Modules.LoadedModulesMetadata[module.Id], -1, new Dictionary<string, object>());

                return CoordinatesParameters.UpdateParameterAction;
            };

            StateData.SetTransformerModule = (module) =>
            {
                ModuleCommand.EnableModule(Modules.LoadedModulesMetadata[module.Id], -1, new Dictionary<string, object>());

                return TransformerParameters.UpdateParameterAction;
            };

            StateData.TransformerModule = () =>
            {
                if (!string.IsNullOrEmpty(TransformerModuleId))
                {
                    return Modules.GetModule(Modules.TransformerModules, TransformerModuleId);
                }
                else
                {
                    return null;
                }

            };

            StateData.CoordinateModule = () =>
            {
                if (!string.IsNullOrEmpty(CoordinatesModuleId))
                {
                    return Modules.GetModule(Modules.CoordinateModules, TransformerModuleId);
                }
                else
                {
                    return null;
                }

            };

            StateData.PlottingModules = () => (from el in PlotActions select Modules.GetModule(Modules.PlottingModules, el.Item1)).ToList();
            StateData.FurtherTransformationModules = () => (from el in FurtherTransformations select Modules.GetModule(Modules.FurtherTransformationModules, el.Item1)).ToList();

            StateData.GetSelectedNode = () => SelectedNode;
            StateData.SetSelectedNode = (value) => SelectedNode = value;

            StateData.TransformerModuleParameterUpdater = () => TransformerParameters.UpdateParameterAction;
            StateData.CoordinatesModuleParameterUpdater = () => CoordinatesParameters.UpdateParameterAction;

            StateData.FurtherTransformationModulesParameterUpdater = (index) => FurtherTransformations[index].Item2.UpdateParameterAction;
            StateData.PlottingModulesParameterUpdater = (index) => PlotActions[index].Item2.UpdateParameterAction;

            StateData.GetTransformerModuleParameters = () => TransformerParameters.Parameters;
            StateData.GetCoordinatesModuleParameters = () => CoordinatesParameters.Parameters;

            StateData.GetFurtherTransformationModulesParamters = (index) => FurtherTransformations[index].Item2.Parameters;
            StateData.GetPlottingModulesParameters = (index) => PlotActions[index].Item2.Parameters;

            StateData.OpenFile = (fileName, deleteAfter) =>
                {
                    try
                    {
                        Program.InputFileName = fileName;
                        OpenCommand.OpenFile(Program.InputFileName, null);
                        LoadCommand.LoadFile(null);

                        if (deleteAfter)
                        {
                            try
                            {
                                File.Delete(fileName);
                            }
                            catch { }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConsoleWrapper.WriteLine();
                        ConsoleWrapper.WriteLine(new ConsoleTextSpan("    An error occurred while opening the file!\n" + ex.Message, 4, ConsoleColor.Red));
                        ConsoleWrapper.WriteLine();
                    }
                };

            StateData.SerializeAllModules = Program.SerializeAllModules;

            ConsoleWrapper.TreatControlCAsInput = true;

            

            ConsoleWrapper.WriteLine("Type \"help\" for a list of available commands");
            ConsoleWrapper.WriteLine();

            while (!ExitCommandLoopHandle.WaitOne(0))
            {
                string command = ReadCommand();

                if (ConsoleWrapper.CursorTop >= ConsoleWrapper.BufferHeight - ConsoleWrapper.WindowHeight)
                {
                    ConsoleWrapper.MoveBufferAndClear();
                }

                try
                {
                    bool result = Commands.ExecuteCommand(command);
                    if (!result)
                    {
                        ConsoleWrapper.WriteLine("Unknown command: " + command);
                    }
                }
                catch (Exception ex)
                {
                    ConsoleWrapper.WriteLine();
                    ConsoleWrapper.WriteLine(new ConsoleTextSpan[]{
                    new ConsoleTextSpan("An error occurred while executing command: ", ConsoleColor.Red),
                    new ConsoleTextSpan(command + "\n"),
                    new ConsoleTextSpan("Error message:", ConsoleColor.Red) });

                    ConsoleWrapper.WriteLine(from el in ex.Message.Split('\n') select new ConsoleTextSpan("  " + el + "\n", 2));
                }
            }
        }

19 Source : WindowsChildProcessState.cs
with MIT License
from asmichi

public void DangerousRetrieveExitCode()
        {
            Debug.replacedert(_exitedWaitHandle.WaitOne(0));

            if (!Kernel32.GetExitCodeProcess(_processHandle, out _exitCode))
            {
                throw new Win32Exception();
            }

            _hasExitCode = true;
        }

19 Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void Disconnect_ClientDisconnects_EventFires()
        {
            var requestReceived = new ManualResetEvent(false);
            var requestCanceled = new ManualResetEvent(false);

            OwinHttpListener listener = CreateServer(
                async env =>
                {
                    GetCallCancelled(env).Register(() => requestCanceled.Set());
                    requestReceived.Set();
                    replacedert.True(requestCanceled.WaitOne(1000));
                },
                HttpServerAddress);

            using (listener)
            {
                var client = new HttpClient();
                var requestTask = client.GetAsync(HttpClientAddress);
                replacedert.True(requestReceived.WaitOne(1000));
                client.CancelPendingRequests();
                replacedert.True(requestCanceled.WaitOne(1000));
                replacedert.Throws<AggregateException>(() => requestTask.Result);
            }
        }

19 Source : OwinWebSocketTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task EndToEnd_EchoData_Success()
        {
            ManualResetEvent echoComplete = new ManualResetEvent(false);
            OwinHttpListener listener = CreateServer(env =>
            {
                var accept = (WebSocketAccept)env["websocket.Accept"];
                replacedert.NotNull(accept);

                accept(
                    null,
                    async wsEnv =>
                    {
                        var sendAsync = wsEnv.Get<WebSocketSendAsync>("websocket.SendAsync");
                        var receiveAsync = wsEnv.Get<WebSocketReceiveAsync>("websocket.ReceiveAsync");
                        var closeAsync = wsEnv.Get<WebSocketCloseAsync>("websocket.CloseAsync");

                        var buffer = new ArraySegment<byte>(new byte[100]);
                        Tuple<int, bool, int> serverReceive = await receiveAsync(buffer, CancellationToken.None);
                        await sendAsync(new ArraySegment<byte>(buffer.Array, 0, serverReceive.Item3),
                            serverReceive.Item1, serverReceive.Item2, CancellationToken.None);
                        replacedert.True(echoComplete.WaitOne(100), "Echo incomplete");
                        await closeAsync((int)WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None);
                    });

                return Task.FromResult(0);
            },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new ClientWebSocket())
                {
                    await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);

                    byte[] sendBody = Encoding.UTF8.GetBytes("Hello World");
                    await client.SendAsync(new ArraySegment<byte>(sendBody), WebSocketMessageType.Text, true, CancellationToken.None);
                    var receiveBody = new byte[100];
                    WebSocketReceiveResult readResult = await client.ReceiveAsync(new ArraySegment<byte>(receiveBody), CancellationToken.None);
                    echoComplete.Set();

                    replacedert.Equal(WebSocketMessageType.Text, readResult.MessageType);
                    replacedert.True(readResult.EndOfMessage);
                    replacedert.Equal(sendBody.Length, readResult.Count);
                    replacedert.Equal("Hello World", Encoding.UTF8.GetString(receiveBody, 0, readResult.Count));
                }
            }
        }

19 Source : OwinHttpListenerTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public void Disconnect_ClientDisconnects_Before_CancellationToken_Created()
        {
            var requestReceived = new ManualResetEvent(false);
            var requestCanceled = new ManualResetEvent(false);

            var clientDisposed = new ManualResetEvent(false);

            OwinHttpListener listener = CreateServer(
                env =>
                {
                    requestReceived.Set();

                    // lets wait for client to be gone
                    replacedert.True(clientDisposed.WaitOne(1000));

                    // the most important part is not to observe CancellationToken before client disconnects

                    GetCallCancelled(env).Register(() => requestCanceled.Set());
                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new HttpClient())
                {
                    var requestTask = client.GetAsync(HttpClientAddress);
                    replacedert.True(requestReceived.WaitOne(1000));
                    client.CancelPendingRequests();

                    replacedert.Throws<AggregateException>(() => requestTask.Result);
                }

                clientDisposed.Set();

                replacedert.True(requestCanceled.WaitOne(1000));
            }
        }

19 Source : OwinWebSocketTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task WebSocketUpgradeAfterHeadersSent_Throws()
        {
            ManualResetEvent sync = new ManualResetEvent(false);
            OwinHttpListener listener = CreateServer(env =>
                {
                    var accept = (WebSocketAccept)env["websocket.Accept"];
                    replacedert.NotNull(accept);

                    // Send a response
                    Stream responseStream = (Stream)env["owin.ResponseBody"];
                    responseStream.Write(new byte[100], 0, 100);
                    sync.Set();

                    replacedert.Throws<InvalidOperationException>(() =>
                    {
                        accept(
                            null,
                            async wsEnv =>
                            {
                                throw new Exception("This wasn't supposed to get called.");
                            });
                    });

                    sync.Set();

                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new ClientWebSocket())
                {
                    try
                    {
                        Task task = client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);
                        replacedert.True(sync.WaitOne(500));
                        await task;
                        replacedert.Equal(string.Empty, "A WebSocketException was expected.");
                    }
                    catch (WebSocketException)
                    {
                    }
                }
            }
        }

19 Source : OwinWebSocketTests.cs
with Apache License 2.0
from aspnet

[Fact]
        public async Task ErrorInWebSocket_Disconnected()
        {
            ManualResetEvent sync = new ManualResetEvent(false);
            OwinHttpListener listener = CreateServer(env =>
                {
                    var accept = (WebSocketAccept)env["websocket.Accept"];
                    replacedert.NotNull(accept);

                    accept(
                        null,
                        async wsEnv =>
                        {
                            sync.Set();
                            throw new Exception("Application WebSocket error.");
                        });

                    return Task.FromResult(0);
                },
                HttpServerAddress);

            using (listener)
            {
                using (var client = new ClientWebSocket())
                {
                    await client.ConnectAsync(new Uri(WsClientAddress), CancellationToken.None);

                    try
                    {
                        replacedert.True(sync.WaitOne(500));
                        await client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                        replacedert.Equal(string.Empty, "A WebSocketException was expected.");
                    }
                    catch (WebSocketException)
                    {
                    }
                }
            }
        }

See More Examples