private async Task WatcherLoop(CancellationToken cancellationToken) { try { Watching = true; await foreach (var(t, evt) in CreateWatchEventEnumerator(_streamReaderCreator, OnError, cancellationToken) .ConfigureAwait(false) ) { OnEvent?.Invoke(t, evt); } } catch (OperationCanceledException) { // ignore } catch (Exception e) { // error when transport error, IOException ect OnError?.Invoke(e); } finally { Watching = false; OnClosed?.Invoke(); } }
public async Task ClosedCall() { if (OnClosed != null) { await OnClosed?.Invoke(); } }
//--------------------------------------------------------------------- void _raiseClosed() { if (OnClosed != null) { OnClosed.Invoke(null, EventArgs.Empty); } }
public void Close <T>() where T : Popup { if (_activePopupStack.IsEmpty() || _activePopupStack.Peek().GetType() != typeof(T)) { return; } Popup popup = _activePopupStack.Get <T>(); popup.AnimateOut(() => { _activePopupStack.Pop(); PreviousPopup = CurrentPopup; CurrentPopup = null; OnClosed?.Invoke(popup.GetType()); popup.Clear(); if (_activePopupStack.Count > 0) { OpenFromStack(); } }); }
public MessageCenter(TransportManager transportManager) { _transportManager = transportManager; _transportManager.OnConnected += (p, e, _) => OnConnected?.Invoke(e.ToUri(p)); _transportManager.OnReceived += OnReceive; _transportManager.OnClosed += (p, e, _) => OnClosed?.Invoke(e.ToUri(p)); }
private void Am_OnAnimationFinished(object sender) { Height = 0; BindedTimedEvent = null; Invalidate(); OnClosed?.Invoke(this); }
public void Close() { if (TradeType == TradeType.Buy) { InputEvent.Instance.Event_SwitchShop.RemoveListener(SwitchMenuToSell); } else { InputEvent.Instance.Event_SwitchShop.RemoveListener(SwitchMenuToBuy); } Left.Deactivate(); Right.Deactivate(); Products = null; UI_NavigatorManager.Instance.Remove(ref uinav_escapeToCloseShop); UI_NavigatorManager.Instance.Remove(ref uinav_tabSellOrBuy); InputEvent.Instance.Event_CloseShop.RemoveAllListener(); UI_Chat_Main.Instance.Dialogue.UpdateDialogue(dialogueAfterShopClosed.ReturnToObject.Dialogue , dialogueAfterShopClosed.ReturnToIndex); dialogueAfterShopClosed = null; OnClosed.Invoke(); }
private void ProcessReceive(object sender, SocketAsyncEventArgs eventArgs) { if (eventArgs.SocketError != SocketError.Success) { Console.Error.WriteLine($"Error {eventArgs.SocketError.ToString()}"); } (var transport, var transportMessage) = ((TcpClientTransport, TransportMessage))eventArgs.UserToken; if (eventArgs.BytesTransferred == 0) { OnClosed?.Invoke(ProtocolType.Tcp, _remoteEndPoint, eventArgs); eventArgs.Dispose(); return; } transportMessage.UpdateBytesReceived(); // Check if we're done if (transportMessage.IsReady) { OnReceived?.Invoke(ProtocolType.Tcp, _remoteEndPoint, transportMessage); transportMessage.Reset(); } StartReceivingAsync(eventArgs); }
/// <summary> /// Webs the socket connect. /// </summary> /// <returns>The socket connect.</returns> public async Task WebSocketConnect(OnRecivedMessage onRecivedMessage = null, OnOpened onOpened = null, OnClosed onClosed = null) { this.onRecivedMessage = onRecivedMessage; this.onOpened = onOpened; this.onClosed = onClosed; if (null != clientWebSocket) { await clientWebSocket.CloseAsync(WebSocketCloseStatus.Empty, "close", CancellationToken.None); } clientWebSocket = new ClientWebSocket(); clientWebSocket.Options.AddSubProtocol("Mixin-Blaze-1"); string token = GenGetJwtToken("/", ""); clientWebSocket.Options.SetRequestHeader("Authorization", "Bearer " + token); using (var cts = new CancellationTokenSource(ReadTimeout)) { Task taskConnect = clientWebSocket.ConnectAsync(new Uri(MIXIN_WEBSOCKET_URL), cts.Token); await taskConnect; } if (clientWebSocket.State == WebSocketState.Open) { onOpened?.Invoke(this, null); } else { Console.WriteLine("Connetced fails: " + clientWebSocket.State); } }
public Task CloseAsync() { if (_socket == null) { throw new InvalidOperationException("Close failed, must connect first."); } else { _tokenSource.Cancel(); _tokenSource.Dispose(); _socket.Abort(); _receiverLoop.Abort(); _senderLoop.Abort(); _socket.Dispose(); WakeSenderLoop(); State = SocketState.Closed; _socket = null; if (serverCloseReason != ServerCloseReason.SocketClosedByClient) { OnClosed?.Invoke(serverCloseReason); } else { OnClosed?.Invoke(ServerCloseReason.SocketClosedByClient); } // SocketClosedByClient return(Task.CompletedTask); } }
public async Task ReceiveAsync() { try { while (Socket.State == WebSocketState.Open) { var buffer = new byte[512]; var result = await Socket.ReceiveAsync(buffer, CancellationToken.None); switch (result.MessageType) { case WebSocketMessageType.Text: if (!result.EndOfMessage) { continue; } var lastIndex = Array.FindLastIndex(buffer, b => b != 0); Array.Resize(ref buffer, lastIndex + 1); OnMessage?.Invoke(this, buffer); continue; case WebSocketMessageType.Close: OnClosed?.Invoke(this); continue; } } } catch { OnClosed?.Invoke(this); } }
/// <summary> /// Closes the session's RTP and control ports. /// </summary> public void Close(string reason) { if (!m_isClosed) { try { string closeReason = reason ?? "normal"; if (m_controlReceiver == null) { logger.LogDebug($"RTPChannel closing, RTP receiver on port {RTPPort}. Reason: {closeReason}."); } else { logger.LogDebug($"RTPChannel closing, RTP receiver on port {RTPPort}, Control receiver on port {ControlPort}. Reason: {closeReason}."); } m_isClosed = true; m_rtpReceiver?.Close(null); m_controlReceiver?.Close(null); OnClosed?.Invoke(closeReason); } catch (Exception excp) { logger.LogError("Exception RTPChannel.Close. " + excp); } } }
/// <summary> /// Closes and dispose associated underlying database transaction/connection asynchronously. /// </summary> /// <param name="cancellationToken">Asynchronous operation cancellation token.</param> /// <returns>Asynchronous operation completion task.</returns> public virtual async Task CloseAsync(CancellationToken cancellationToken = default) { OnClosing?.Invoke(this, EventArgs.Empty); DisposeCommand(); if (TransactionAsync != null && _closeTransaction) { TransactionAsync.Dispose(); TransactionAsync = null; } if (_connection != null) { if (_disposeConnection) { await _connection.DisposeAsync().ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); _connection = null; } else if (_closeConnection) { await _connection.CloseAsync().ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); } } OnClosed?.Invoke(this, EventArgs.Empty); }
public async Task StartAsync() { await HandleCommunicationAsync(); OnConnectionStateChanged?.Invoke(this, new ConnectionStateChangedEventArgs(ConnectionState.Closed)); OnClosed?.Invoke(this, null); }
/// <summary> /// Called when the window closes, used to shutdown client systems. /// </summary> private void Window_Closed(object sender, EventArgs e) { if (VR != null) { VR.Stop(); VR = null; } Sounds.Shutdown(); if (RawGamePad != null) { RawGamePad.Dispose(); RawGamePad = null; } if (LocalServer != null) { // TODO: ManualReset object? Object tlock = new Object(); bool done = false; LocalServer.ShutDown(() => { lock (tlock) { done = true; } }); bool b = false; while (!b) { Thread.Sleep(250); lock (tlock) { b = done; } } } // TODO: Cleanup! OnClosed?.Invoke(); Environment.Exit(0); }
public void Close() { lock (_closeConnLock) { if (_closed) { return; } _closed = true; } OnClosed?.Invoke(this, new SSRelayEventArgs(_server)); try { _connection.Shutdown(SocketShutdown.Both); _connection.Close(); encryptor?.Dispose(); decryptor?.Dispose(); } catch (Exception e) { this.Log().Error(e, ""); } }
public override Dialog OnCreateDialog(Bundle savedInstanceState) { var builder = new AlertDialog.Builder(Activity); var inflater = Activity.LayoutInflater; var selectedDate = GetSelectedDate(); var dialog = inflater.Inflate(Resource.Layout.date_picker_dialog, null); _monthPicker = (NumberPicker)dialog.FindViewById(Resource.Id.picker_month); _yearPicker = (NumberPicker)dialog.FindViewById(Resource.Id.picker_year); InitializeMonthPicker(selectedDate.Month); InitializeYearPicker(selectedDate.Year); SetMaxMinDate(MaxDate, MinDate); builder.SetView(dialog) .SetPositiveButton("Ok", (sender, e) => { selectedDate = new DateTime(_yearPicker.Value, _monthPicker.Value, DefaultDay); OnDateTimeChanged?.Invoke(dialog, selectedDate); }) .SetNegativeButton("Cancel", (sender, e) => { Dialog.Cancel(); OnClosed?.Invoke(dialog, selectedDate); }) .SetNeutralButton("Limpar", (sender, e) => { Dialog.Cancel(); OnClosed?.Invoke(dialog, selectedDate); }); return(builder.Create()); }
private void SetEventHandlers(Options opts) { opts.AsyncErrorEventHandler += (sender, args) => OnAsyncError?.Invoke(this, ErrorEventArguments.FromNatsEntity(args)); opts.ServerDiscoveredEventHandler += (sender, args) => OnServerDiscovered?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args)); opts.ClosedEventHandler += (sender, args) => OnClosed?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args)); opts.DisconnectedEventHandler += (sender, args) => OnDisconnected?.Invoke(this, ConnectionEventArguments.FromNatsEntity(args)); }
private async Task StartSend() { while (await reader.WaitToReadAsync()) { if (reader.TryRead(out ArraySegment <byte> message)) { if (clientWebSocket.State != WebSocketState.Open) { throw new WebSocketException(WebSocketError.InvalidState, "Error Sending Message. WebSocket State is: " + clientWebSocket.State); } int messageCount = (int)Math.Ceiling((double)message.Count / SendChunkSize); for (int i = 0; i < messageCount; i++) { int offset = SendChunkSize * i; bool endOfMessage = (i == messageCount - 1); int count = endOfMessage ? message.Count - offset : SendChunkSize; await clientWebSocket.SendAsync(new ArraySegment <byte>(message.Array, offset, count), WebSocketMessageType.Binary, endOfMessage, cancellationToken).ConfigureAwait(false); } } } // close the socket (listener will therminate after that) clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None).Wait(); IsConnected.Reset(); OnClosed?.Invoke(null, EventArgs.Empty); }
private async Task <string> ReceiveAsync(ClientWebSocket webSocket) { // TODO: Probably should optimize this (better resource allocation/management) byte[] temporaryBuffer = new byte[8192]; byte[] buffer = new byte[8192 * 16]; int offset = 0; bool end = false; while (!end) { WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(temporaryBuffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { OnClosed?.Invoke(result.CloseStatus, result.CloseStatusDescription).GetAwaiter(); Connected = false; Console.WriteLine(new LogMessage(LogSeverity.Info, "Lavalink", "Disconnected from Lavalink node")); } else { temporaryBuffer.CopyTo(buffer, offset); offset += result.Count; temporaryBuffer = new byte[8192]; if (result.EndOfMessage) { end = true; } } } return(Encoding.UTF8.GetString(buffer)); }
private void ProcessReceive(object sender, SocketAsyncEventArgs eventArgs) { if (eventArgs.SocketError != SocketError.Success) { Console.Error.WriteLine($"Error {eventArgs.SocketError.ToString()}"); } OnConnected?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, eventArgs); if (eventArgs.BytesTransferred == 0) { OnClosed?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, eventArgs); eventArgs.Dispose(); return; } (var transport, var transportMessage) = ((UdpHostTransport, TransportMessage))eventArgs.UserToken; transportMessage.UpdateBytesReceived(); // For now, UDP messages cannot extend across a single message OnReceived?.Invoke(ProtocolType.Udp, eventArgs.RemoteEndPoint, transportMessage); transportMessage.Reset(UdpPacketSize); _autoResetEvent.Set(); }
/// <summary> /// 当关闭时 /// </summary> /// <param name="obj">socket对象</param> private void OnSocketClosed(object obj) { receiveState.Reset(); if (OnClosed != null) { OnClosed.Invoke(this, lastException); } }
private Task SocketError(SocketErrorEventArgs e) { Console.WriteLine("Socket Error!"); Console.WriteLine(e.ToString()); Close(); OnClosed?.Invoke(); return(Task.CompletedTask); }
public void Open(string url, string protocol = null) { _clientWebSocketConnection = ClientWebSocketWrapper.Create(url); _clientWebSocketConnection.OnConnect(_ => OnOpened?.Invoke()); _clientWebSocketConnection.OnDisconnect(_ => OnClosed?.Invoke()); _clientWebSocketConnection.OnMessage((s, _) => OnMessage?.Invoke(s)); _clientWebSocketConnection.Connect().Wait(); }
/// <summary> /// Close picker popup /// </summary> public async Task Close() { await LeftCalendar.CalculateCalendar(); await RightCalendar.CalculateCalendar(); Visible = false; await OnClosed.InvokeAsync(null); }
public virtual void Close() { if (isOpened) { Hide(); OnClosed.Dispatch(this); isOpened = false; } }
private void StartMonitor() { _monitorTask = Task.Run(() => { _monitorRunning = true; var needsReconnect = false; try { var lastState = State; while (_ws != null && !_disposedValue) { if (lastState == State) { Thread.Sleep(200); continue; } OnStateChanged?.Invoke(State, lastState); if (State == WebSocketState.Open) { OnOpened?.Invoke(); } if ((State == WebSocketState.Closed || State == WebSocketState.Aborted) && !_reconnecting) { if (lastState == WebSocketState.Open && !_disconnectCalled && _reconnectStrategy != null && !_reconnectStrategy.AreAttemptsComplete()) { // go through the reconnect strategy // Exit the loop and start async reconnect needsReconnect = true; break; } OnClosed?.Invoke(_ws.CloseStatus ?? WebSocketCloseStatus.Empty); if (_ws.CloseStatus != null && _ws.CloseStatus != WebSocketCloseStatus.NormalClosure) { OnError?.Invoke(new Exception(_ws.CloseStatus + " " + _ws.CloseStatusDescription)); } } lastState = State; } } catch (Exception ex) { OnError?.Invoke(ex); } if (needsReconnect && !_reconnecting && !_disconnectCalled) #pragma warning disable 4014 { DoReconnect(); } #pragma warning restore 4014 _monitorRunning = false; }); }
public void Dispose() { if (IsOpen) { Rollback(); } _transactionFlavor?.Dispose(); OnClosed?.Invoke(this, new TransactionEventArgs(_transactionDomain)); }
public void Open(string url, string protocol = null) { socket = protocol == null ? new WebSocket(url) : new WebSocket(url, protocol); socket.OnOpen += delegate { OnOpened?.Invoke(); }; socket.OnClose += delegate { OnClosed?.Invoke(); }; socket.OnError += (sender, args) => OnError?.Invoke(args.Message); socket.OnMessage += (sender, args) => OnMessage?.Invoke(args.Data); socket.Connect(); }
public async void Close() { if (IsAlive()) { await clientWebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); IsConnected.Reset(); OnClosed?.Invoke(null, EventArgs.Empty); } }
void OnClosedHandler(OnClosed onClosed) { _form = null; }
void OnClosedHandler(OnClosed onClosed) { if (onClosed.DriveControl == _driveControl) { LogInfo("Form Closed"); _mainPort.Post(new DsspDefaultDrop(DropRequestType.Instance)); } }
/// <summary> /// Handle the Form Closed event for the Dashboard Form /// </summary> /// <param name="onClosed">The closed message</param> private void OnClosedHandler(OnClosed onClosed) { if (onClosed.ObstacleAvoidanceForm == this.obstacleAvoidanceForm) { LogInfo("Form Closed"); } }