public void Open() { _messageQueue.Open(); ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(() => { while (!_messageQueue.IsClosed) { try { var sended = _historyMessageAdapter.SendOutMessage(); var block = !sended; Message message; while (_messageQueue.TryDequeue(out message, true, block)) { NewOutMessage?.Invoke(message); block = false; } } catch (Exception ex) { _errorHandler(ex); } } })) .Name("History emulation channel thread.") .Launch(); }
protected virtual void Start() { if (IsStarted) { return; } IsStarted = true; IsStopping = false; _doneEvt.Reset(); _lastLimitsUpdateTime = DateTime.MinValue; //_nextIntervalStartsAt = DateTime.MinValue; _requestsPerSecond = 0; CurrentAutoRequest = null; _recentRequests.Clear(); UpdateLimitsIfNecessary(); ThreadingHelper .Thread(() => { try { ModuleThreadFunc(); } catch (Exception e) { Client.RaiseError(new ETradeException(LocalizedStrings.Str3362Params.Put(_name), e)); } finally { _doneEvt.Set(); } }) .Background(true) .Name("etrade_" + _name) .Launch(); }
private void OnLoginOk(ISession session) { try { Session = session; SendOutMessage(new ConnectMessage()); } catch (Exception ex) { SendError <ConnectMessage>(ex); } try { Session.Subscribe(new HeartbeatSubscriptionRequest(), () => { }, CreateErrorHandler("HeartbeatSubscriptionRequest")); ThreadingHelper .Thread(() => Session.Start()) .Background(true) .Name("LMAX Export thread") .Launch(); } catch (Exception ex) { SendOutError(ex); } }
/// <summary> /// The method is called when the <see cref="Strategy.Start"/> method has been called and the <see cref="Strategy.ProcessState"/> state has been taken the <see cref="ProcessStates.Started"/> value. /// </summary> protected override void OnStarted() { var storateRegistry = new StorageRegistry(); var drive = Environment.GetValue <IMarketDataDrive>("Drive"); if (drive != null) { storateRegistry.DefaultDrive = drive; } StorateRegistry = storateRegistry; ThreadingHelper .Thread(() => { try { OnAnalyze(); } catch (Exception ex) { this.AddErrorLog(ex); ex.LogError(); } }) .Name("{0} analyze thread.".Put(Name)) .Culture(CultureInfo.InvariantCulture) .Launch(); }
public void StartListening(Action <Exception> processError) { if (processError == null) { throw new ArgumentNullException(nameof(processError)); } ThreadingHelper .Thread(() => { try { while (!IsDisposed) { var func = ProcessResponse; if (func == null || !func(this)) { break; } } } catch (Exception ex) { if (!IsDisposed) { processError(ex); } } }) .Name("IBSocket response") .Culture(CultureInfo.InvariantCulture) .Start(); }
void IMessageProcessor.Start() { _messageQueue.Open(); ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(() => { while (!_messageQueue.IsClosed) { try { MessageItem item; if (!TryDequeue(out item)) { break; } _newMessage.SafeInvoke(item.Item1, item.Item2); } catch (Exception ex) { _errorHandler(ex); } } _stopped.SafeInvoke(); })) .Name("{0}. Messages thread.".Put(Name)) //.Culture(CultureInfo.InvariantCulture) .Launch(); }
/// <summary> /// Initializes a new instance of the <see cref="StorageCandleSource"/>. /// </summary> public StorageCandleSource() { ThreadingHelper .Thread(OnLoading) .Background(true) .Name(GetType().Name) .Launch(); }
/// <summary> /// Initialize <see cref="StorageCandleBuilderSource{T}"/>. /// </summary> protected StorageCandleBuilderSource() { ThreadingHelper .Thread(OnLoading) .Background(true) .Name(GetType().Name) .Launch(); }
/// <summary> /// Отправить сообщение. /// </summary> /// <param name="message">Сообщение.</param> protected override void OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Connect: { if (_loadingThread != null) { throw new InvalidOperationException(LocalizedStrings.Str1116); } LoadedEventCount = 0; _running = true; _disconnecting = false; _loadingThread = ThreadingHelper .Thread(OnLoad) .Name("HistoryMessageAdapter. Loader thread") .Launch(); SendOutMessage(new ConnectMessage()); return; } case MessageTypes.Disconnect: { var running = _running; _running = false; if (_loadingThread == null) { // отправляем LastMessage только если не отправили его из OnLoad if (!running) { SendOutMessage(new LastMessage()); } SendOutMessage(new DisconnectMessage()); } else { // DisconnectMessage должен быть отправлен самым последним _disconnecting = true; _syncRoot.Pulse(); } return; } case MessageTypes.MarketData: ProcessMarketDataMessage((MarketDataMessage)message); return; } SendOutMessage(message); }
public StudioCommandService() { ThreadingHelper .Thread(Process) .Background(true) .Culture(CultureInfo.InvariantCulture) .Name("Studio command service thread") .Launch(); }
public void ConnectPusher() { _ws = new ClientWebSocket(); _ws.ConnectAsync(new Uri("wss://ws.pusherapp.com/app/de504dc5763aeef9ff52?client=PC-Orbit&version=1.0&protocol=7"), _source.Token).Wait(); _connected = true; ThreadingHelper.Thread(OnReceive).Launch(); }
private void OnLoginOk(ISession session) { try { _session = session; _session.HeartbeatReceived += OnSessionHeartbeatReceived; _session.EventStreamSessionDisconnected += OnSessionEventStreamSessionDisconnected; _session.InstructionRejected += OnSessionInstructionRejected; _session.AccountStateUpdated += OnSessionAccountStateUpdated; _session.OrderChanged += OnSessionOrderChanged; _session.PositionChanged += OnSessionPositionChanged; _session.OrderExecuted += OnSessionOrderExecuted; _session.EventStreamFailed += OnSessionEventStreamFailed; _session.HistoricMarketDataReceived += OnSessionHistoricMarketDataReceived; _session.MarketDataChanged += OnSessionMarketDataChanged; _session.OrderBookStatusChanged += OnSessionOrderBookStatusChanged; SendOutMessage(new ConnectMessage()); } catch (Exception ex) { SendError <ConnectMessage>(ex); } try { _session.Subscribe(new HeartbeatSubscriptionRequest(), () => { }, CreateErrorHandler("HeartbeatSubscriptionRequest")); ThreadingHelper .Thread(() => { try { _session.Start(); } catch (Exception ex) { SendOutError(ex); } }) .Background(true) .Name("LMAX session thread") .Launch(); } catch (Exception ex) { SendOutError(ex); } }
/// <summary> /// Initializes a new instance of the <see cref="CachedBasketMarketDataStorage{T}"/>. /// </summary> public CachedBasketMarketDataStorage(BasketMarketDataStorage <T> basketStorage) { if (basketStorage == null) { throw new ArgumentNullException(nameof(basketStorage)); } _basketStorage = basketStorage; _cancellationToken = new CancellationTokenSource(); ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(OnLoad)) .Name("Cached marketdata storage thread.") .Launch(); }
private void LookupPanel_OnLookup(Security filter) { SecuritiesAll.SecurityFilter = filter.Code; var downloader = Task as ISecurityDownloader; if (downloader == null) { return; } BusyIndicator.BusyContent = LocalizedStrings.Str2834; BusyIndicator.IsBusy = true; ThreadingHelper .Thread(() => { var securities = ConfigManager.GetService <IEntityRegistry>().Securities; try { downloader.Refresh(securities, filter, s => { }, () => _isClosed); } catch (Exception ex) { ex.LogError(); } try { securities.DelayAction.WaitFlush(); } catch (Exception ex) { ex.LogError(); } try { this.GuiAsync(() => BusyIndicator.IsBusy = false); } catch (Exception ex) { ex.LogError(); } }) .Launch(); }
/// <summary> /// Добавить сообщение в очередь на отправку. /// </summary> /// <param name="message">Сообщение.</param> private void EnqueueMessage(LogMessage message) { if (message.IsDispose) { _queue.Close(); return; } _queue.Enqueue(Tuple.Create(GetSubject(message), message.Message)); lock (_queue.SyncRoot) { if (_isThreadStarted) { return; } _isThreadStarted = true; ThreadingHelper.Thread(() => { try { using (var email = CreateClient()) { while (true) { Tuple <string, string> m; if (!_queue.TryDequeue(out m)) { break; } email.Send(From, To, m.Item1, m.Item2); } } lock (_queue.SyncRoot) _isThreadStarted = false; } catch (Exception ex) { Trace.WriteLine(ex); } }).Name("Email log queue").Launch(); } }
private void LookupPanel_OnLookup(Security filter) { //SecurityPicker.Securities.Clear(); SecurityPicker.SecurityFilter = filter.Code; var downloaders = MainWindow.Instance.Tasks.Where(t => t.Settings.IsEnabled).OfType <ISecurityDownloader>().ToArray(); if (downloaders.IsEmpty()) { return; } BusyIndicator.BusyContent = LocalizedStrings.Str2834; BusyIndicator.IsBusy = true; ThreadingHelper .Thread(() => { try { var securities = ConfigManager.TryGetService <IEntityRegistry>().Securities; SecurityPicker.Securities.AddRange(securities .Lookup(filter) .Where(s => !s.IsAllSecurity())); downloaders.ForEach(d => d.Refresh(securities, filter, SecurityPicker.Securities.Add, () => _isDisposed)); } catch (Exception ex) { ex.LogError(); } try { this.GuiAsync(() => BusyIndicator.IsBusy = false); } catch (Exception ex) { ex.LogError(); } }) .Launch(); }
/// <summary> /// Initializes a new instance of the <see cref="CachedBasketMarketDataStorage{T}"/>. /// </summary> public CachedBasketMarketDataStorage(BasketMarketDataStorage <T> basketStorage) { if (basketStorage == null) { throw new ArgumentNullException(nameof(basketStorage)); } _basketStorage = basketStorage; _basketStorage.InnerStorages.Add(new InMemoryMarketDataStorage <TimeMessage>(null, null, GetTimeLine)); _cancellationToken = new CancellationTokenSource(); MaxMessageCount = 1000000; ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(OnLoad)) .Name("Cached marketdata storage thread.") .Launch(); }
private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { if (DatePicker.Value == null) { MessageBox.Show(LocalizedStrings.Str3750, Title, MessageBoxButton.OK, MessageBoxImage.Information); return; } var date = ((DateTime)DatePicker.Value).Date; bool isSuccess; BusyIndicator.IsBusy = true; ThreadingHelper.Thread(() => { try { var ticks = MainWindow.Instance.Trader.GetHistoricalLevel1(_security.ToSecurityId(), date, date.AddDays(1), out isSuccess); this.GuiAsync(() => { BusyIndicator.IsBusy = false; L1Grid.Messages.Clear(); L1Grid.Messages.AddRange(ticks); }); } catch (Exception ex) { this.GuiAsync(() => { BusyIndicator.IsBusy = false; new MessageBoxBuilder().Text(ex.Message).Owner(this).Show(); }); } }).Launch(); }
/// <summary> /// Open channel. /// </summary> public void Open() { _messageQueue.Open(); ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(() => { while (!_messageQueue.IsClosed) { try { Message message; if (!_messageQueue.TryDequeue(out message)) { break; } //if (!(message is TimeMessage) && message.GetType().Name != "BasketMessage") // Console.WriteLine("<< ({0}) {1}", System.Threading.Thread.CurrentThread.Name, message); _msgStat.Remove(message); NewOutMessage?.Invoke(message); } catch (Exception ex) { _errorHandler(ex); } } Closed?.Invoke(); })) .Name($"{Name} channel thread.") //.Culture(CultureInfo.InvariantCulture) .Launch(); }
public void Open() { _messageQueue.Open(); ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(() => { while (!_messageQueue.IsClosed) { try { var sended = _historyMessageAdapter.SendOutMessage(); KeyValuePair <DateTimeOffset, Message> pair; if (!_messageQueue.TryDequeue(out pair, true, !sended)) { if (!sended) { break; } } else { NewOutMessage.SafeInvoke(pair.Value); } } catch (Exception ex) { _errorHandler(ex); } } })) .Name("History emulation channel thread.") .Launch(); }
/// <summary> /// Open channel. /// </summary> public void Open() { _messageQueue.Open(); ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(() => { while (!_messageQueue.IsClosed) { try { KeyValuePair <DateTimeOffset, Message> pair; if (!_messageQueue.TryDequeue(out pair)) { break; } //if (!(message is TimeMessage) && message.GetType().Name != "BasketMessage") // Console.WriteLine("<< ({0}) {1}", System.Threading.Thread.CurrentThread.Name, message); _msgStat.Remove(pair.Value); NewOutMessage.SafeInvoke(pair.Value); } catch (Exception ex) { _errorHandler(ex); } } Closed.SafeInvoke(); })) .Name("{0} channel thread.".Put(Name)) //.Culture(CultureInfo.InvariantCulture) .Launch(); }
/// <summary> /// Обновить таблицу. Выполняется асинхронно. /// </summary> /// <param name="storageRegistry">Хранилище маркет-данных.</param> /// <param name="security">Инструмент.</param> /// <param name="format">Формат данных.</param> /// <param name="drive">Хранилище.</param> public void BeginMakeEntries(IStorageRegistry storageRegistry, Security security, StorageFormats format, IMarketDataDrive drive) { if (storageRegistry == null) { throw new ArgumentNullException("storageRegistry"); } lock (_syncObject) { _query = new Query(storageRegistry, security, format, drive); _isChanged = true; if (_isFlushing) { return; } _isFlushing = true; ThreadingHelper .Thread(() => CultureInfo.InvariantCulture.DoInCulture(OnFlush)) .Launch(); } }
private void InitializeCommands() { var cmdSvc = ConfigManager.GetService <IStudioCommandService>(); cmdSvc.Register <OpenMarketDataSettingsCommand>(this, true, cmd => OpenMarketDataPanel(cmd.Settings)); cmdSvc.Register <RefreshSecurities>(this, false, cmd => ThreadingHelper .Thread(() => { var entityRegistry = ConfigManager.GetService <IEntityRegistry>(); var count = 0; var progress = 0; try { using (var client = new RemoteStorageClient(new Uri(cmd.Settings.Path))) { var credentials = cmd.Settings.Credentials; client.Credentials.Login = credentials.Login; client.Credentials.Password = credentials.Password; foreach (var secType in cmd.Types.TakeWhile(secType => !cmd.IsCancelled())) { if (secType == SecurityTypes.Future) { var from = DateTime.Today.AddMonths(-4); var to = DateTime.Today.AddMonths(4); var expiryDates = from.GetExpiryDates(to); foreach (var expiryDate in expiryDates.TakeWhile(d => !cmd.IsCancelled())) { client.Refresh(entityRegistry.Securities, new Security { Type = secType, ExpiryDate = expiryDate }, s => { entityRegistry.Securities.Save(s); _connector.SendOutMessage(s.ToMessage()); count++; }, cmd.IsCancelled); } } else { // для акций передаем фиктивное значение ExpiryDate, чтобы получить инструменты без даты экспирации var expiryDate = secType == SecurityTypes.Stock ? DateTime.Today : (DateTime?)null; client.Refresh(entityRegistry.Securities, new Security { Type = secType, ExpiryDate = expiryDate }, s => { entityRegistry.Securities.Save(s); _connector.SendOutMessage(s.ToMessage()); count++; }, cmd.IsCancelled); } cmd.ProgressChanged(++progress); } } } catch (Exception ex) { ex.LogError(); } if (cmd.IsCancelled()) { return; } try { cmd.WhenFinished(count); } catch (Exception ex) { ex.LogError(); } }) .Launch()); }
/// <summary> /// Send message. /// </summary> /// <param name="message">Message.</param> protected override void OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { TryResume(); LoadedMessageCount = 0; _disconnecting = _loadingThread != null; _loadingThread = null; if (!_disconnecting) { SendOutMessage(new ResetMessage()); } break; } case MessageTypes.Connect: { if (_loadingThread != null) { throw new InvalidOperationException(LocalizedStrings.Str1116); } SendOutMessage(new ConnectMessage { LocalTime = StartDate.LocalDateTime }); return; } case MessageTypes.Disconnect: { _disconnecting = true; TryResume(); return; } case MessageTypes.SecurityLookup: { var lookupMsg = (SecurityLookupMessage)message; //ThreadingHelper.Thread(() => //{ // try // { SecurityProvider.LookupAll().ForEach(security => { SendOutMessage(security.Board.ToMessage()); var secMsg = security.ToMessage(); secMsg.OriginalTransactionId = lookupMsg.TransactionId; SendOutMessage(secMsg); //SendOutMessage(new Level1ChangeMessage { SecurityId = security.ToSecurityId() } // .Add(Level1Fields.StepPrice, security.StepPrice) // .Add(Level1Fields.MinPrice, security.MinPrice) // .Add(Level1Fields.MaxPrice, security.MaxPrice) // .Add(Level1Fields.MarginBuy, security.MarginBuy) // .Add(Level1Fields.MarginSell, security.MarginSell)); }); SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = lookupMsg.TransactionId }); // } // catch (Exception ex) // { // SendOutError(ex); // } //}).Name("History sec lookup").Start(); return; } case MessageTypes.MarketData: case ExtendedMessageTypes.HistorySource: ProcessMarketDataMessage((MarketDataMessage)message); return; case ExtendedMessageTypes.EmulationState: var stateMsg = (EmulationStateMessage)message; var isSuspended = false; switch (stateMsg.State) { case EmulationStates.Starting: { if (_loadingThread != null) { TryResume(); break; } _loadingThread = ThreadingHelper .Thread(OnLoad) .Name("HistoryMessageAdapter") .Launch(); break; } case EmulationStates.Suspending: { lock (_suspendLock) _isSuspended = true; isSuspended = true; break; } } SendOutMessage(message); if (isSuspended) { SendOutMessage(new EmulationStateMessage { State = EmulationStates.Suspended }); } return; } //SendOutMessage(message); }
private void InitializeCommands() { var cmdSvc = ConfigManager.GetService <IStudioCommandService>(); cmdSvc.Register <OpenMarketDataSettingsCommand>(this, true, cmd => OpenMarketDataPanel(cmd.Settings)); cmdSvc.Register <RefreshSecurities>(this, false, cmd => ThreadingHelper .Thread(() => { var entityRegistry = ConfigManager.GetService <IEntityRegistry>(); var count = 0; var progress = 0; try { using (var client = new RemoteStorageClient(new Uri(cmd.Settings.Path))) { var credentials = cmd.Settings.Credentials; client.Credentials.Login = credentials.Login; client.Credentials.Password = credentials.Password; foreach (var secType in cmd.Types.TakeWhile(secType => !cmd.IsCancelled())) { if (secType == SecurityTypes.Future) { var from = DateTime.Today.AddMonths(-4); var to = DateTime.Today.AddMonths(4); var expiryDates = from.GetExpiryDates(to); foreach (var expiryDate in expiryDates.TakeWhile(d => !cmd.IsCancelled())) { client.Refresh(entityRegistry.Securities, new Security { Type = secType, ExpiryDate = expiryDate }, s => { entityRegistry.Securities.Save(s); _connector.SendOutMessage(s.ToMessage()); count++; }, cmd.IsCancelled); } } else { // для акций передаем фиктивное значение ExpiryDate, чтобы получить инструменты без даты экспирации var expiryDate = secType == SecurityTypes.Stock ? DateTime.Today : (DateTime?)null; client.Refresh(entityRegistry.Securities, new Security { Type = secType, ExpiryDate = expiryDate }, s => { entityRegistry.Securities.Save(s); _connector.SendOutMessage(s.ToMessage()); count++; }, cmd.IsCancelled); } cmd.ProgressChanged(++progress); } } } catch (Exception ex) { ex.LogError(); } if (cmd.IsCancelled()) { return; } try { cmd.WhenFinished(count); } catch (Exception ex) { ex.LogError(); } }) .Launch()); cmdSvc.Register <CreateSecurityCommand>(this, true, cmd => { var entityRegistry = ConfigManager.GetService <IEntityRegistry>(); ISecurityWindow wnd; if (cmd.SecurityType == typeof(Security)) { wnd = new SecurityCreateWindow(); } else { throw new InvalidOperationException(LocalizedStrings.Str2140Params.Put(cmd.SecurityType)); } wnd.ValidateId = id => { if (entityRegistry.Securities.ReadById(id) != null) { return(LocalizedStrings.Str2927Params.Put(id)); } return(null); }; if (!((Window)wnd).ShowModal(Application.Current.GetActiveOrMainWindow())) { return; } entityRegistry.Securities.Save(wnd.Security); _connector.SendOutMessage(wnd.Security.ToMessage()); cmd.Security = wnd.Security; }); cmdSvc.Register <SetDefaultEmulationSettingsCommand>(this, false, cmd => { _emulationSettings.Load(cmd.Settings.Save()); _layoutManager.FlushSettings(); }); }
/// <summary> /// Запустить. /// </summary> public void Start() { if (State != TaskStates.Stopped) { return; } _currentErrorCount = 0; ThreadingHelper.Thread(() => { try { WaitIfNecessary(TimeSpan.Zero); State = TaskStates.Starting; OnStarting(); var attempts = 60; while (State == TaskStates.Starting && attempts-- > 0) { WaitIfNecessary(TimeSpan.FromSeconds(1)); } if (State == TaskStates.Starting) { this.AddErrorLog(LocalizedStrings.Str2191); } while (State == TaskStates.Started) { try { var interval = OnProcess(); if (interval == TimeSpan.MaxValue) { Stop(); break; } // сбрасываем счетчик при успешной итерации _currentErrorCount = 0; WaitIfNecessary(interval); } catch (Exception ex) { HandleError(ex); WaitIfNecessary(TimeSpan.FromSeconds(5)); } } } catch (Exception ex) { this.AddErrorLog(ex); this.AddErrorLog(LocalizedStrings.Str2192); } finally { try { OnStopped(); } catch (Exception ex) { this.AddErrorLog(ex); } Stopped.SafeInvoke(this); State = TaskStates.Stopped; } }) .Name("{0} Task thread".Put(Name)) .Launch(); }
public AlertService() { ThreadingHelper .Thread(() => { try { var player = new MediaPlayer(); var fileName = Path.Combine(UserConfig.Instance.MainFolder, "alert.mp3"); if (!File.Exists(fileName)) { File.WriteAllBytes(fileName, Properties.Resources.Alert); } player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute)); var logManager = ConfigManager.GetService <LogManager>(); using (var speech = new SpeechSynthesizer()) using (var client = new NotificationClient()) using (player.MakeDisposable(p => p.Close())) { while (!IsDisposed) { Tuple <AlertTypes, string, string, DateTime> alert; if (!_alerts.TryDequeue(out alert)) { break; } try { switch (alert.Item1) { case AlertTypes.Sound: player.Play(); break; case AlertTypes.Speech: speech.Speak(alert.Item2); break; case AlertTypes.Popup: GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow { Title = alert.Item2, Message = alert.Item3, Time = alert.Item4 }.Show()); break; case AlertTypes.Sms: client.SendSms(alert.Item2); break; case AlertTypes.Email: client.SendEmail(alert.Item2, alert.Item3); break; case AlertTypes.Log: logManager.Application.AddWarningLog(() => "Оповещение! В {0} случилось '{1}'.{2}" .Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3)); break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception ex) { ex.LogError(); } } } } catch (Exception ex) { ex.LogError(); } }) .Name("Alert thread") .Launch(); }
/// <summary> /// Подключиться к серверу. /// </summary> public void Connect() { _logReceiver.AddInfoLog("[{0}] Connecting...", Name); if (_socket != null) { throw new InvalidOperationException(LocalizedStrings.Str2152); } _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { _socket.Connect(Address); lock (_syncDisconnect) IsExportStarted = true; ThreadingHelper .Thread(() => { var buf = new StringBuilder(); var buffer = new byte[1024]; try { while (true) { if (_socket == null) { throw new InvalidOperationException(LocalizedStrings.Str2153); } if (_socket.Poll(500000, SelectMode.SelectRead)) { // http://stackoverflow.com/questions/2661764/how-to-check-if-a-socket-is-connected-disconnected-in-c if (_socket.Available == 0) { throw new InvalidOperationException(LocalizedStrings.Str1611); } var bytesRecv = _socket.Receive(buffer, 0, buffer.Length, SocketFlags.None); buf.Append(Encoding.ASCII.GetString(buffer, 0, bytesRecv)); var index = buf.LastIndexOf('\n'); if (index == -1) { continue; } var res = buf.ToString(0, index + 1); var reply = res.Split("\n").Select(v => v.TrimEnd('\r', '\n')); if (index < buf.Length - 1) { buf.Remove(0, index + 1); } else { buf.Clear(); } try { foreach (var line in reply) { _logReceiver.AddDebugLog("[{0}] Response: {1}", Name, line); ProcessReply.SafeInvoke(line); } } catch (Exception ex) { _logReceiver.AddErrorLog(ex); } } lock (_syncDisconnect) { if (IsExportStarted) { continue; } _logReceiver.AddInfoLog(LocalizedStrings.Str2154Params, Name); Monitor.Pulse(_syncDisconnect); break; } } } catch (ObjectDisposedException ex) { ConnectionError.SafeInvoke(new InvalidOperationException(LocalizedStrings.Str2155, ex)); } catch (Exception ex) { ConnectionError.SafeInvoke(ex); } try { _socket.Shutdown(SocketShutdown.Both); } catch (Exception ex) { _logReceiver.AddErrorLog(ex); } _socket.Close(); _socket = null; _logReceiver.AddInfoLog(LocalizedStrings.Str2156Params, Name); }) .Name("IQFeed '{0}' thread".Put(Name)) .Culture(CultureInfo.InvariantCulture) .Start(); Request("S,SET PROTOCOL,5.1"); _logReceiver.AddInfoLog("[{0}] Connected", Name); } catch { _socket.Close(); _socket = null; throw; } }
public void Add(TData data) { lock (_data.SyncRoot) { if (!_data.TryAdd(data)) { return; } _dataVersion++; switch (_currState) { case States.Starting: return; case States.Started: //_currState = States.Starting; _response.Close(); return; case States.Stopping: _currState = States.Starting; return; case States.Stopped: _currState = States.Starting; break; default: throw new ArgumentOutOfRangeException(); } } ThreadingHelper.Thread(() => { var errorCount = 0; const int maxErrorCount = 10; while (!_parent.IsDisposed) { var dataVersion = 0; try { var url = new Url(_parent._streamingUrl + "/v1/" + _methodName); TData[] cachedData; lock (_data.SyncRoot) { switch (_currState) { case States.Starting: lock (_data.SyncRoot) { cachedData = _data.Cache; dataVersion = _dataVersion; } break; case States.Started: case States.Stopped: throw new InvalidOperationException(); case States.Stopping: _currState = States.Stopped; return; default: throw new ArgumentOutOfRangeException(); } } _fillQuery(url.QueryString, cachedData); var request = WebRequest.Create(url); // for non-sandbox requests if (_parent._token != null) { request.Headers.Add("Authorization", "Bearer " + _parent._token.To <string>()); } request.Headers.Add("X-Accept-Datetime-Format", "UNIX"); using (var response = request.GetResponse()) { lock (_data.SyncRoot) { switch (_currState) { case States.Starting: // new items may be added or removed if (dataVersion < _dataVersion) { continue; } _currState = States.Started; _response = response; break; case States.Started: case States.Stopped: throw new InvalidOperationException(); case States.Stopping: continue; default: throw new ArgumentOutOfRangeException(); } } using (var reader = new StreamReader(response.GetResponseStream())) { string line; var lineErrorCount = 0; const int maxLineErrorCount = 100; while (!_parent.IsDisposed && (line = reader.ReadLine()) != null) { try { _newLine(JsonConvert.DeserializeObject <TResponse>(line)); lineErrorCount = 0; } catch (Exception ex) { _parent.NewError.SafeInvoke(ex); if (++lineErrorCount >= maxLineErrorCount) { //this.AddErrorLog("Max error {0} limit reached.", maxLineErrorCount); break; } } } } } } catch (Exception ex) { bool needLog; lock (_data.SyncRoot) { needLog = dataVersion == _dataVersion; _currState = _data.Count > 0 ? States.Starting : States.Stopping; _response = null; } if (needLog) { _parent.NewError.SafeInvoke(ex); if (++errorCount >= maxErrorCount) { //this.AddErrorLog("Max error {0} limit reached.", maxErrorCount); break; } } else { errorCount = 0; } } finally { lock (_data.SyncRoot) _response = null; } } }) .Name("Oanda " + _methodName) .Launch(); }
/// <summary> /// Initializes a new instance of the <see cref="AlertService"/>. /// </summary> /// <param name="dumpDir">Temp files directory.</param> public AlertService(string dumpDir) { if (dumpDir.IsEmpty()) { throw new ArgumentNullException(nameof(dumpDir)); } ThreadingHelper .Thread(() => { try { var player = new MediaPlayer(); var fileName = Path.Combine(dumpDir, "alert.mp3"); if (!File.Exists(fileName)) { Properties.Resources.Alert.Save(fileName); } player.Open(new Uri(fileName, UriKind.RelativeOrAbsolute)); var logManager = ConfigManager.GetService <LogManager>(); using (var speech = new SpeechSynthesizer()) using (var client = new NotificationClient()) using (player.MakeDisposable(p => p.Close())) { while (!IsDisposed) { Tuple <AlertTypes, string, string, DateTimeOffset> alert; if (!_alerts.TryDequeue(out alert)) { break; } try { switch (alert.Item1) { case AlertTypes.Sound: player.Play(); break; case AlertTypes.Speech: speech.Speak(alert.Item2); break; case AlertTypes.Popup: GuiDispatcher.GlobalDispatcher.AddAction(() => new AlertPopupWindow { Title = alert.Item2, Message = alert.Item3, Time = alert.Item4.UtcDateTime }.Show()); break; case AlertTypes.Sms: client.SendSms(alert.Item2); break; case AlertTypes.Email: client.SendEmail(alert.Item2, alert.Item3); break; case AlertTypes.Log: logManager.Application.AddWarningLog(() => LocalizedStrings.Str3033Params .Put(alert.Item4, alert.Item2, Environment.NewLine + alert.Item3)); break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception ex) { ex.LogError(); } } } } catch (Exception ex) { ex.LogError(); } }) .Name("Alert thread") .Launch(); }