private void ProcessUpdate() { Task.Factory.StartNew(() => { while (!_cts.Token.IsCancellationRequested) { string symbol; if (_symbolToUpdate.TryDequeue(out symbol)) { try { var d = _candles[symbol]; if (_symbolsInitialized.Contains(symbol)) { _qbStore.AddCandle(d.Symbol, d.Interval, d.Time, d.Open, d.Close, d.High, d.Low, d.Volume, true, true); } else { _symbolToInitQueue2.Enqueue(symbol); } } catch (Exception ex) { OnExceptionOccured?.Invoke(this, Exchange, ex); } finally { _isProcessCandleListOngoing = false; } } } }, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
public void Exit() { isRunning = false; if (communicator != null) { Status = BundleStatus.Exiting; try { communicator.shutdown(); communicator.destroy(); Status = BundleStatus.Shutdown; } catch (System.Exception ex) { Status = BundleStatus.Exception; OnExceptionOccured?.Invoke(ex); } communicator = null; } else { Status = BundleStatus.Unknown; } counter = 0; }
private void ProcessInit() { Task.Factory.StartNew(() => { while (!_cts.Token.IsCancellationRequested) { string symbol; if (_symbolToInitQueue1.TryDequeue(out symbol) || _symbolToInitQueue2.TryDequeue(out symbol)) { try { if (_isFillGap) { this.InitQuoteBasic(symbol); } else { this.InitQuoteBasic2(symbol); } } catch (Exception ex) { OnExceptionOccured?.Invoke(this, Exchange, ex); } } } }, _cts.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); }
public static void LogException(Exception e, [CallerMemberName] string previousMethodName = null, [CallerLineNumber] int callermemberlineNo = 0, [CallerFilePath] string calledFilePath = null) { if (e == null) { return; } LogMessageReceived?.Invoke(null, new LogMessageEventArgs(e.ToString(), DateTime.Now, LogEnums.LogLevel.EXCEPTION, previousMethodName, callermemberlineNo, calledFilePath)); OnExceptionOccured?.Invoke(null, new OnExceptionMessageEventArgs(e, DateTime.Now, previousMethodName, callermemberlineNo, calledFilePath)); }
private void Stop() { _clock.OnSecondPassed -= OnSecondPassed; try { _action(); } catch (Exception e) { OnExceptionOccured?.Invoke(e); } }
public bool TryRequest(Action request) { if (!IsMaxed()) { try { request(); } catch (Exception e) { OnExceptionOccured?.Invoke(e); } Enqueue(); return(true); } return(false); }
public void Start(string args, ACMCloseFlag close = ACMCloseFlag.CloseOff, ACMHeartbeatFlag heartbeat = ACMHeartbeatFlag.HeartbeatOff) { acmClose = close; acmHeartbeat = heartbeat; if (communicator == null || communicator.isShutdown()) { Status = BundleStatus.Starting; try { const int SIZE_MAX = 128 * 1024 * 1024; var initData = new InitializationData(); initData.properties = Util.createProperties(); initData.properties.setProperty("Ice.Trace.Network", "2"); initData.properties.setProperty("Ice.MessageSizeMax", $"{SIZE_MAX}"); initData.properties.setProperty("Filesystem.MaxFileSize", $"{SIZE_MAX}"); initData.properties.setProperty("Ice.ACM.Close", $"{(int)acmClose}"); initData.properties.setProperty("Ice.ACM.Heartbeat", $"{(int)acmHeartbeat}"); communicator = Util.initialize(initData); var pos = args.IndexOf(':'); var name = "SimpleMessenger"; if (pos > 0) { name = args.Substring(0, pos); args = args.Substring(pos + 1).TrimStart(); } ObjectAdapter objectAdapter = communicator.createObjectAdapterWithEndpoints("SimpleMessengerAdapter", args); servant = new WorkerImpl(OnMethodInvoked); Identity id = Util.stringToIdentity(name); objectAdapter.add(servant, id); objectAdapter.activate(); Status = BundleStatus.Running; communicator.waitForShutdown(); Status = BundleStatus.Idle; } catch (System.Exception ex) { Status = BundleStatus.Exception; OnExceptionOccured?.Invoke(ex); } } else { Status = BundleStatus.Unknown; } }
private async void _qcStore_OnQuoteCaptureDataAdded(object sender, string exchange, IQuoteCapture quote, int numAppended) { try { var symbol = quote.Symbol; if (_symbolsInitialized.Contains(symbol)) { _qbStore.AddQuoteCapture(quote, true); } else //initialize IQuoteBasicBase { this.InitQuoteBasic(symbol); } } catch (Exception ex) { OnExceptionOccured?.Invoke(this, this.Exchange, ex); } }
public void Stop() { if (communicator != null) { Status = BundleStatus.Stopping; try { communicator.shutdown(); } catch (System.Exception ex) { Status = BundleStatus.Exception; OnExceptionOccured?.Invoke(ex); } Status = BundleStatus.Stopped; } else { Status = BundleStatus.Unknown; } }
private void DoWork(object obj) { ThreadStart innerWork = obj as ThreadStart; if (innerWork != null && !m_interrupted) { try { innerWork.Invoke(); } catch (Exception exc) { OnExceptionOccured?.Invoke(this, new ThreadExceptionEventArgs(exc)); } } lock (m_threadLocker) { m_runningThreads--; Monitor.Pulse(m_threadLocker); } }
public void SignalError(Object Sender, DateTime Timestamp, Exception Exception) { OnExceptionOccured?.Invoke(Sender, Timestamp, Exception); }
/// <summary> /// Initialize the TCP server using the given parameters. /// </summary> /// <param name="IIPAddress">The listening IP address(es)</param> /// <param name="Port">The listening port</param> /// <param name="ServiceBanner">Service banner.</param> /// <param name="ServerThreadName">The optional name of the TCP server thread.</param> /// <param name="ServerThreadPriority">The optional priority of the TCP server thread.</param> /// <param name="ServerThreadIsBackground">Whether the TCP server thread is a background thread or not.</param> /// <param name="ConnectionIdBuilder">An optional delegate to build a connection identification based on IP socket information.</param> /// <param name="ConnectionThreadsNameBuilder">An optional delegate to set the name of the TCP connection threads.</param> /// <param name="ConnectionThreadsPriorityBuilder">An optional delegate to set the priority of the TCP connection threads.</param> /// <param name="ConnectionThreadsAreBackground">Whether the TCP connection threads are background threads or not (default: yes).</param> /// <param name="ConnectionTimeout">The TCP client timeout for all incoming client connections in seconds (default: 30 sec).</param> /// <param name="MaxClientConnections">The maximum number of concurrent TCP client connections (default: 4096).</param> /// <param name="Autostart">Start the TCP server thread immediately (default: no).</param> public TCPServer(IIPAddress IIPAddress, IPPort Port, String ServiceBanner = __DefaultServiceBanner, String ServerThreadName = null, ThreadPriority ServerThreadPriority = ThreadPriority.AboveNormal, Boolean ServerThreadIsBackground = true, ConnectionIdBuilder ConnectionIdBuilder = null, ConnectionThreadsNameBuilder ConnectionThreadsNameBuilder = null, ConnectionThreadsPriorityBuilder ConnectionThreadsPriorityBuilder = null, Boolean ConnectionThreadsAreBackground = true, TimeSpan?ConnectionTimeout = null, UInt32 MaxClientConnections = __DefaultMaxClientConnections, Boolean Autostart = false) { #region TCP Socket this._IPAddress = IIPAddress; this._Port = Port; this._IPSocket = new IPSocket(_IPAddress, _Port); this._TCPListener = new TcpListener(new System.Net.IPAddress(_IPAddress.GetBytes()), _Port.ToInt32()); #endregion #region TCP Server this._ServiceBanner = (ServiceBanner.IsNotNullOrEmpty()) ? ServiceBanner : __DefaultServiceBanner; this.ServerThreadName = (ServerThreadName != null) ? ServerThreadName : __DefaultServerThreadName + this.IPSocket.ToString(); this.ServerThreadPriority = ServerThreadPriority; this.ServerThreadIsBackground = ServerThreadIsBackground; #endregion #region TCP Connections this._TCPConnections = new ConcurrentDictionary <IPSocket, TCPConnection>(); this.ConnectionIdBuilder = (ConnectionIdBuilder != null) ? ConnectionIdBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP:" + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port; this.ConnectionThreadsNameBuilder = (ConnectionThreadsNameBuilder != null) ? ConnectionThreadsNameBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => "TCP thread " + RemoteIPSocket.IPAddress + ":" + RemoteIPSocket.Port; this.ConnectionThreadsPriorityBuilder = (ConnectionThreadsPriorityBuilder != null) ? ConnectionThreadsPriorityBuilder : (Sender, Timestamp, LocalSocket, RemoteIPSocket) => ThreadPriority.AboveNormal; this.ConnectionThreadsAreBackground = ConnectionThreadsAreBackground; this._ConnectionTimeout = ConnectionTimeout.HasValue ? ConnectionTimeout.Value : TimeSpan.FromSeconds(30); this._MaxClientConnections = MaxClientConnections; #endregion #region TCP Listener Thread this.CancellationTokenSource = new CancellationTokenSource(); this.CancellationToken = CancellationTokenSource.Token; _ListenerThread = new Thread(() => { #if __MonoCS__ // Code for Mono C# compiler #else Thread.CurrentThread.Name = this.ServerThreadName; Thread.CurrentThread.Priority = this.ServerThreadPriority; Thread.CurrentThread.IsBackground = this.ServerThreadIsBackground; #endif #region SetSocketOptions // IOControlCode.* // fd.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, tcpKeepalive); // bytes.PutInteger(endian, tcpKeepalive, 0); // bytes.PutInteger(endian, tcpKeepaliveIdle, 4); // bytes.PutInteger(endian, tcpKeepaliveIntvl, 8); // fd.IOControl(IOControlCode.KeepAliveValues, (byte[])bytes, null); #endregion try { _IsRunning = true; while (!_StopRequested) { // Wait for a new/pending client connection while (!_StopRequested && !_TCPListener.Pending()) { Thread.Sleep(5); } // Break when a server stop was requested if (_StopRequested) { break; } // Processing the pending client connection within its own task var NewTCPClient = _TCPListener.AcceptTcpClient(); // var NewTCPConnection = _TCPListener.AcceptTcpClientAsync(). // ContinueWith(a => new TCPConnection(this, a.Result)); // // ConfigureAwait(false); // Store the new connection //_SocketConnections.AddOrUpdate(_TCPConnection.Value.RemoteSocket, // _TCPConnection.Value, // (RemoteEndPoint, TCPConnection) => TCPConnection); Task.Factory.StartNew(Tuple => { try { var _Tuple = Tuple as Tuple <TCPServer, TcpClient>; var NewTCPConnection = new ThreadLocal <TCPConnection>( () => new TCPConnection(_Tuple.Item1, _Tuple.Item2) ); #region Copy ExceptionOccured event handlers //foreach (var ExceptionOccuredHandler in MyEventStorage) // _TCPConnection.Value.OnExceptionOccured += ExceptionOccuredHandler; #endregion #region OnNewConnection // If this event closes the TCP connection the OnNotification event will never be fired! // Therefore you can use this event for filtering connection initiation requests. OnNewConnection?.Invoke(NewTCPConnection.Value.TCPServer, NewTCPConnection.Value.ServerTimestamp, NewTCPConnection.Value.RemoteSocket, NewTCPConnection.Value.ConnectionId, NewTCPConnection.Value); if (!NewTCPConnection.Value.IsClosed) { OnNotification?.Invoke(NewTCPConnection.Value); } #endregion } catch (Exception e) { while (e.InnerException != null) { e = e.InnerException; } OnExceptionOccured?.Invoke(this, DateTime.Now, e); Console.WriteLine(DateTime.Now + " " + e.Message + Environment.NewLine + e.StackTrace); } }, new Tuple <TCPServer, TcpClient>(this, NewTCPClient)); } #region Shutdown // Request all client connections to finish! foreach (var _SocketConnection in _TCPConnections) { _SocketConnection.Value.StopRequested = true; } // After stopping the TCPListener wait for // all client connections to finish! while (_TCPConnections.Count > 0) { Thread.Sleep(5); } #endregion } #region Exception handling catch (Exception Exception) { var OnExceptionLocal = OnExceptionOccured; if (OnExceptionLocal != null) { OnExceptionLocal(this, DateTime.Now, Exception); } } #endregion _IsRunning = false; }); #endregion if (Autostart) { Start(); } }
private void ExceptionOccured(string errorMessage) { // Make sure someone is listening to event OnExceptionOccured?.Invoke(errorMessage); }
protected void client_OnExceptionOccured(object sender, string exchange, Exception ex) { OnExceptionOccured?.Invoke(sender, exchange, ex); }
public async void Start(string args, bool hold = false, bool ami = false, ACMHeartbeatFlag heartbeat = ACMHeartbeatFlag.HeartbeatOff) { Hold = hold; amiEnabled = ami; acmHeartbeat = heartbeat; if (communicator == null || communicator.isShutdown()) { Status = BundleStatus.Starting; try { const int SIZE_MB = 128; const int SIZE_MAX = SIZE_MB * 1024 * 1024; if (contentSizeMB < 0 || contentSizeMB > SIZE_MB) { contentSizeMB = 1; } var initData = new InitializationData(); initData.properties = Util.createProperties(); initData.properties.setProperty("Ice.MessageSizeMax", $"{SIZE_MAX}"); initData.properties.setProperty("Filesystem.MaxFileSize", $"{SIZE_MAX}"); initData.properties.setProperty("Ice.ACM.Heartbeat", $"{(int)acmHeartbeat}"); communicator = Util.initialize(initData); WorkerPrx workerPrx = WorkerPrxHelper.checkedCast(communicator.stringToProxy(args)); if (workerPrx == null) { throw new ApplicationException("Invalid Proxy"); } isRunning = true; Status = BundleStatus.Running; while (isRunning && communicator != null) { if (Hold) { Thread.Sleep(100); continue; } var operation = operations[counter % operations.Count]; ++counter; OnMethodInvoked?.Invoke(operation, amiEnabled); if (amiEnabled) { try { var result = workerPrx?.PerformActionEx(operation, contentSizeMB); } catch (OperationException ex) { OnExceptionOccured?.Invoke(ex); } Thread.Sleep(rand.Next(200, 1000)); } else { try { var result = workerPrx?.PerformAction(operation, contentSizeMB); } catch (OperationException ex) { OnExceptionOccured?.Invoke(ex); } Thread.Sleep(500); } } Status = BundleStatus.Idle; } catch (System.Exception ex) { Status = BundleStatus.Exception; OnExceptionOccured?.Invoke(ex); } } else { isRunning = false; Status = BundleStatus.Unknown; } }