/// <summary> /// Sets the listener in listening state on a particular end-point. /// </summary> /// <param name="address">End-point to listen to.</param> /// <param name="thread">The thread to use for listening.</param> public Task ListenAsync(ServiceAddress address, EventThread thread) { ServerAddress = address; Thread = thread; ConnectionManager = new ConnectionManager(thread); var tcs = new TaskCompletionSource <int>(this); Thread.Post(state => { var tcs2 = (TaskCompletionSource <int>)state; try { var listener = ((Listener)tcs2.Task.AsyncState); listener.ListenSocket = listener.CreateListenSocket(); tcs2.SetResult(0); } catch (Exception ex) { tcs2.SetException(ex); } }, tcs); return(tcs.Task); }
public void Dispose() { if (this._eventThread != null) { this._eventThread.Dispose(); this._eventThread = null; } GC.SuppressFinalize(this); }
/// <summary> /// Adds the specified event to the state machine's event queue. /// </summary> /// <param name="nsfEvent">The event to queue.</param> /// <param name="isPriorityEvent">Flag indicating if the event should be queued to the back of the queue (false) or the front of the queue (true).</param> /// <param name="logEventQueued">Flag indicating if an event queued trace should be added to the trace log.</param> private void queueEvent(NSFEvent nsfEvent, bool isPriorityEvent, bool logEventQueued) { if (!isTopStateMachine()) { TopStateMachine.queueEvent(nsfEvent, isPriorityEvent, logEventQueued); return; } lock (stateMachineMutex) { // Do not allow events to be queued if terminating or terminated, // except for run to completion event, which may be queued if terminating to allow proper semantics to continue until terminated. if ((TerminationStatus == NSFEventHandlerTerminationStatus.EventHandlerTerminated) || ((TerminationStatus == NSFEventHandlerTerminationStatus.EventHandlerTerminating) && (nsfEvent != runToCompletionEvent))) { return; } // Handle special case of terminate event by setting status and queuing a single terminate event. // Terminate event must be the last event queued to guarantee safe deletion when it is handled. if (nsfEvent == terminateEvent) { if (TerminationStatus == NSFEventHandlerTerminationStatus.EventHandlerReady) { TerminationStatus = NSFEventHandlerTerminationStatus.EventHandlerTerminating; } } // Event limit detection looks for too many events queued for the state machine. // If more than the specified number of events are queued, the state machine will remove // its queued events, call the event limit actions, and stop after executing any events queued // by the limit actions. if ((EventLimitDetectionEnabled) && (QueuedEvents == EventLimit)) { EventThread.removeEventsFor(this); QueuedEvents = 0; EventLimitActions.execute(new NSFStateMachineContext(this, null, null, null, nsfEvent)); // Stop the state machine so that no more event processing occurs until started again stopStateMachine(); NSFTraceLog.PrimaryTraceLog.addTrace(NSFTraceTags.ErrorTag, NSFTraceTags.SourceTag, Name, NSFTraceTags.MessageTag, "EventLimit"); return; } nsfEvent.Destination = this; EventThread.queueEvent(nsfEvent, isPriorityEvent, logEventQueued); ++QueuedEvents; } }
public async Task StartAsync( string pipeName, ServiceAddress address, EventThread thread) { _pipeName = pipeName; await ListenAsync(address, thread).ConfigureAwait(false); await Thread.PostAsync(state => ((ListenerPrimary)state).PostCallback(), this).ConfigureAwait(false); }
public void Reset() { EventThread.Enqueue("Reset", () => { #if VERSION0 Task.Delay(TimeSpan.FromMilliseconds(500)).Wait(); StopService(); Task.Delay(TimeSpan.FromMilliseconds(1000)).Wait(); StartService(); #else PS.ClearMessages(); MainTaskConfigured = false; #endif }); }
public void Stop() { if (disposed) { throw new ObjectDisposedException(GetType().Name); } started = false; protocolTimer.Change(Timeout.Infinite, Timeout.Infinite); if (engineMutex.WaitOne()) { try { if (appPortMutex.WaitOne()) { try { outputThread.Abort(); outputThread = null; appPort.Close(); appPort.Dispose(); appPort = null; engine = null; } finally { appPortMutex.ReleaseMutex(); } } else { throw new Exception("Failed to lock application port mutex"); } } finally { engineMutex.ReleaseMutex(); } } else { throw new Exception("Failed to lock protocol engine mutex"); } }
/// <summary> /// Handles an event. /// </summary> /// <param name="nsfEvent">The event to handle.</param> /// <returns>Status indicating if the event was handled or not.</returns> /// <remarks> /// This method is for use only by the North State Framework's internal logic. /// It calls the actions associated with the event, if any. /// </remarks> public NSFEventStatus handleEvent(NSFEvent nsfEvent) { // Handle status changing events if ((nsfEvent == startEvent)) { RunStatus = NSFEventHandlerRunStatus.EventHandlerStarted; } else if (nsfEvent == stopEvent) { RunStatus = NSFEventHandlerRunStatus.EventHandlerStopped; } else if (nsfEvent == terminateEvent) { TerminationStatus = NSFEventHandlerTerminationStatus.EventHandlerTerminated; EventThread.removeEventHandler(this); return(NSFEventStatus.NSFEventHandled); } // Don't process events if stopped if (RunStatus == NSFEventHandlerRunStatus.EventHandlerStopped) { return(NSFEventStatus.NSFEventUnhandled); } // Process the event bool actionsToExecute = false; lock (eventHandlerMutex) { if (eventReactions.ContainsKey(nsfEvent.Id)) { actionsToExecute = true; } } if (actionsToExecute) { eventReactions[nsfEvent.Id].execute(new NSFEventContext(this, nsfEvent)); return(NSFEventStatus.NSFEventHandled); } else { return(NSFEventStatus.NSFEventUnhandled); } }
public Task StartAsync( string pipeName, ServiceAddress address, EventThread thread) { _pipeName = pipeName; _buf = thread.Loop.Libuv.buf_init(_ptr, 4); ServerAddress = address; Thread = thread; ConnectionManager = new ConnectionManager(thread); DispatchPipe = new UvPipeHandle(); var tcs = new TaskCompletionSource <int>(this); Thread.Post(state => StartCallback((TaskCompletionSource <int>)state), tcs); return(tcs.Task); }
public SactaProxy(bool WebEnabled = true) { InitializeComponent(); if (WebEnabled) { SactaProxyWebApp = new SactaProxyWebApp(() => History); SactaProxyWebApp.UserActivityEvent += (sender, args) => { EventThread?.Enqueue("OnUserActivityEvent", () => { var idh = args.InOut ? HistoryItems.UserLogin : args.Cause == "" ? HistoryItems.UserLogout : HistoryItems.UserErrorAccess; History?.Add(idh, args.User, "", "", "", args.Cause); }); }; } else { SactaProxyWebApp = null; } }
public SocketOutput( EventThread thread, UvStreamHandle socket, MemoryPool memory, Connection connection, ConnectionId connectionId, IThreadPool threadPool, Queue <UvWriteReq> writeReqPool) { _thread = thread; _socket = socket; _connection = connection; _connectionId = connectionId; _threadPool = threadPool; _tasksPending = new Queue <WaitingTask>(_initialTaskQueues); _writeContextPool = new Queue <WriteContext>(_maxPooledWriteContexts); _writeReqPool = writeReqPool; _head = memory.Lease(); _tail = _head; }
public async Task <bool> CheckpointAsync(EventThread item) { var parameters = new DynamicParameters(); parameters.Add("hash", item.Hash); parameters.Add("workerId", item.WorkerId); parameters.Add("Checkpoint", item.Checkpoint); parameters.Add("LockExpirationTime", item.LockExpirationTime); using (var connection = new SqlConnection(_connectionStrings.DefaultConnection)) { await connection.OpenAsync().ConfigureAwait(false); var result = (int)await connection.ExecuteScalarAsync( "[dbo].[EventThread_Checkpoint]", commandType : CommandType.StoredProcedure, param : parameters) .ConfigureAwait(false); return(result >= 1); } }
void ListenOnServiceBusQueue() { /* Create Queue client and listen on message */ _sbQueueClient = QueueClient.CreateFromConnectionString(_sbConnectionString, _sbEventActionQueue); OnMessageOptions options = new OnMessageOptions(); options.MaxConcurrentCalls = 1; options.AutoComplete = true; string messageBody = ""; _isRunning = true; _sbQueueClient.OnMessage((message) => { try { // Process message from queue. messageBody = message.GetBody <string>(); _appLogger.Info("EventAction Task onMessage: " + messageBody); _incomeMessage++; JObject jsonMessage = JObject.Parse(messageBody); EventThread eventAction = new EventThread(jsonMessage); Thread eventActionThread = new Thread(new ThreadStart(eventAction.ThreadProc)); eventActionThread.IsBackground = false; eventActionThread.Start(); _processedMessage++; } catch (Exception ex) { // Indicates a problem, unlock message in subscription. _failMessage++; StringBuilder logMessage = new StringBuilder(); logMessage.AppendLine("EventAction Task Exception: " + ex.Message); logMessage.AppendLine("EventAction Task Message: " + messageBody); _appLogger.Error(logMessage); } }, options); }
protected void Dispose(bool disposing) { if (!disposed) { if (disposing) { if (started) { Stop(); } protocolTimer.Dispose(); } application = null; config = null; engine = null; appPort = null; outputThread = null; disposed = true; } }
public static void ManualEventTest() { ManualResetEvent evtObj = new ManualResetEvent(false); EventThread mt1 = new EventThread("EventThread #1", evtObj); Console.WriteLine("Main thread waiting for event"); // Ожидать уведомление о событии evtObj.WaitOne(); Console.WriteLine("Main thread get signal from " + mt1.Thrd.Name); // Установить событийный объект в исходное состояние evtObj.Reset(); mt1 = new EventThread("EventThread #2", evtObj); // Ожидать уведомление о событии. evtObj.WaitOne(); Console.WriteLine("Main thread get signal from " + mt1.Thrd.Name); }
public void queueEvent(NSFEvent nsfEvent) { lock (eventHandlerMutex) { // Do not allow events to be queued if terminating or terminated (i.e. not ready) if (TerminationStatus != NSFEventHandlerTerminationStatus.EventHandlerReady) { return; } // Handle special case of terminate event by setting status and queuing a single terminate event. // Terminate event must be the last event queued to guarantee safe deletion when it is handled. if (nsfEvent == terminateEvent) { if (TerminationStatus == NSFEventHandlerTerminationStatus.EventHandlerReady) { TerminationStatus = NSFEventHandlerTerminationStatus.EventHandlerTerminating; } } nsfEvent.Destination = this; EventThread.queueEvent(nsfEvent, false, LoggingEnabled); } }
public ConnectionManager(EventThread thread) { this.EventThread = thread; Timer.PeriodicCall(TimeSpan.FromSeconds(5), this.CheckAllAlive); }
/// <summary> /// Gets the thread time for a particular thread. /// </summary> /// <param name="thread">The thread to query.</param> /// <returns>The time elapsed in the frame in any state.</returns> public double GetTime(EventThread thread) { if (!this.Map.ContainsKey(thread)) throw new ArgumentOutOfRangeException("Thread #" + thread + " is not contained within the set."); return this.Map[thread].Sum(); }
public void Start() { if (disposed) { throw new ObjectDisposedException(GetType().Name); } if (engineMutex.WaitOne()) { try { if (appPortMutex.WaitOne()) { try { try { engine = new GarminProtocolEngine((short)((int)settings["gpsProductId"].Value), (short)((int)settings["gpsSoftwareVersion"].Value), (string)settings["gpsProductDescription"].Value, (uint)((long)settings["gpsUnitId"].Value), (int)settings["snrMin"].Value, (int)settings["snrMax"].Value); appPort = application.GetPort(this, (string)settings["appPort"].Value); appPort.Read += new PortReadEvent(appPort_Read); appPort.Error += new PortErrorEvent(appPort_Error); appPort.Open(); outputThread = new EventThread(new EventThreadCallback(OutputThreadCallback)); outputThread.Priority = ThreadPriority.Normal; outputThread.Start(); protocolTimer.Change(0, 1000); } catch { protocolTimer.Change(Timeout.Infinite, Timeout.Infinite); if (outputThread != null) { outputThread.Abort(); outputThread = null; } if (appPort != null) { appPort.Close(); appPort.Dispose(); appPort = null; } engine = null; throw; } } finally { appPortMutex.ReleaseMutex(); } } else { throw new Exception("Failed to lock application port mutex"); } } finally { engineMutex.ReleaseMutex(); } } else { throw new Exception("Failed to lock protocol engine mutex"); } started = true; }
/// <summary> /// Increments the time spend switched on. /// </summary> /// <param name="thread">The thread to increment.</param> /// <param name="elapsed">The time spent in that state.</param> public void IncrementOnCoreTime(EventThread thread, double elapsed) { if (!this.OnCoreMap.ContainsKey(thread)) this.OnCoreMap.Add(thread, 0); this.OnCoreMap[thread] += elapsed; }
/// <summary> /// Increments the time for a particular thread/state combination. /// </summary> /// <param name="thread">The thread to increment.</param> /// <param name="state">The state of the thread.</param> /// <param name="elapsed">The time spent in that state.</param> public void IncrementTime(EventThread thread, ThreadState state, double elapsed) { if (!this.Map.ContainsKey(thread)) this.Map.Add(thread, new double[8]); this.Map[thread][(int)state] += elapsed; }
public void Stop() { if (disposed) throw new ObjectDisposedException(GetType().Name); started = false; protocolTimer.Change(Timeout.Infinite, Timeout.Infinite); if (engineMutex.WaitOne()) { try { if (appPortMutex.WaitOne()) { try { outputThread.Abort(); outputThread = null; appPort.Close(); appPort.Dispose(); appPort = null; engine = null; } finally { appPortMutex.ReleaseMutex(); } } else throw new Exception("Failed to lock application port mutex"); } finally { engineMutex.ReleaseMutex(); } } else throw new Exception("Failed to lock protocol engine mutex"); }
public void Start() { if (disposed) throw new ObjectDisposedException(GetType().Name); if (engineMutex.WaitOne()) { try { if (appPortMutex.WaitOne()) { try { try { engine = new GarminProtocolEngine((short)((int)settings["gpsProductId"].Value), (short)((int)settings["gpsSoftwareVersion"].Value), (string)settings["gpsProductDescription"].Value, (uint)((long)settings["gpsUnitId"].Value), (int)settings["snrMin"].Value, (int)settings["snrMax"].Value); appPort = application.GetPort(this, (string)settings["appPort"].Value); appPort.Read += new PortReadEvent(appPort_Read); appPort.Error += new PortErrorEvent(appPort_Error); appPort.Open(); outputThread = new EventThread(new EventThreadCallback(OutputThreadCallback)); outputThread.Priority = ThreadPriority.Normal; outputThread.Start(); protocolTimer.Change(0, 1000); } catch { protocolTimer.Change(Timeout.Infinite, Timeout.Infinite); if (outputThread != null) { outputThread.Abort(); outputThread = null; } if (appPort != null) { appPort.Close(); appPort.Dispose(); appPort = null; } engine = null; throw; } } finally { appPortMutex.ReleaseMutex(); } } else throw new Exception("Failed to lock application port mutex"); } finally { engineMutex.ReleaseMutex(); } } else throw new Exception("Failed to lock protocol engine mutex"); started = true; }
protected void Dispose(bool disposing) { if (! disposed) { if (disposing) { if (started) Stop(); protocolTimer.Dispose(); } application = null; config = null; engine = null; appPort = null; outputThread = null; disposed = true; } }
/// <summary> /// Handles an event. /// </summary> /// <param name="nsfEvent">The event to handle.</param> /// <returns>Status indicating if the event was handled or not.</returns> /// <remarks> /// This method is for use only by the North State Framework's internal logic. /// It processes the event using UML defined behavior, including run to completion. /// </remarks> public NSFEventStatus handleEvent(NSFEvent nsfEvent) { lock (stateMachineMutex) { --QueuedEvents; // This should only happen if events are queued without using the queueEvent method if (QueuedEvents < 0) { QueuedEvents = 0; } } // Handle status changing events if ((nsfEvent == startEvent)) { RunStatus = NSFEventHandlerRunStatus.EventHandlerStarted; } else if (nsfEvent == stopEvent) { RunStatus = NSFEventHandlerRunStatus.EventHandlerStopped; } else if (nsfEvent == terminateEvent) { TerminationStatus = NSFEventHandlerTerminationStatus.EventHandlerTerminated; EventThread.removeEventHandler(this); return(NSFEventStatus.NSFEventHandled); } else if (nsfEvent == resetEvent) { reset(); } // Don't process events if stopped if (RunStatus == NSFEventHandlerRunStatus.EventHandlerStopped) { return(NSFEventStatus.NSFEventUnhandled); } // If not already active, enter state machine at the root if (!active) { enter(new NSFStateMachineContext(this, this, null, null, startEvent), false); } // Process the event NSFEventStatus eventStatus = NSFEventStatus.NSFEventUnhandled; try { eventStatus = processEvent(nsfEvent); if (eventStatus == NSFEventStatus.NSFEventHandled) { runToCompletion(); } // Consecutive loop detection looks for too many events without the state machine pausing. // If more than the specified number of transitions occur without a pause, the state machine will remove // its queued events, call the consecutive loop limit actions, and stop after executing any events queued // by the actions. if (ConsecutiveLoopDetectionEnabled) { ++consecutiveLoopCount; if (consecutiveLoopCount == ConsecutiveLoopLimit) { lock (stateMachineMutex) { EventThread.removeEventsFor(this); QueuedEvents = 0; } ConsecutiveLoopLimitActions.execute(new NSFStateMachineContext(this, null, null, null, nsfEvent)); // Stop the state machine so that no more event processing occurs until started again stopStateMachine(); // Reset consecutive loop count in case state machine is started again consecutiveLoopCount = 0; NSFTraceLog.PrimaryTraceLog.addTrace(NSFTraceTags.ErrorTag, NSFTraceTags.SourceTag, Name, NSFTraceTags.MessageTag, "ConsecutiveLoopLimit"); } else if (QueuedEvents == 0) { // If no events are queued for this state machine, then it has paused, indicating it's not in an infinite loop. consecutiveLoopCount = 0; } } } catch (Exception exception) { handleException(new Exception(nsfEvent.Name + " event handling exception", exception)); } return(eventStatus); }
protected void MainProcessing() { Logger.Info <SactaProxy>("Arrancando Servicio."); MainTaskSync = new System.Threading.ManualResetEvent(false); EventThread.Start(); MainTaskConfigured = ConfigureService(); StartWebServer(); History.Add(HistoryItems.ServiceStarted); do { EventThread.Enqueue("MainProcessing", () => { try { if (MainTaskConfigured == false) { StopManagers(true); StopWebServer(); MainTaskConfigured = ConfigureService(); StartWebServer(); } GlobalStateManager.MainStandbyCheck((isDual, isMain) => { if (isDual) { if (isMain && !PS.IsStarted) { //Logger.Info<SactaProxy>("Entrando en Modo DUAL-MAIN"); History.Add(HistoryItems.ServiceInMode, "", "", "Master"); StartManagers(); } else if (!isMain && PS.IsStarted) { //Logger.Info<SactaProxy>("Entrando en Modo DUAL-STANDBY"); History.Add(HistoryItems.ServiceInMode, "", "", "Standby"); StopManagers(); } } else { if (!PS.IsStarted) { //Logger.Info<SactaProxy>("Entrando en Modo SINGLE"); History.Add(HistoryItems.ServiceInMode, "", "", "Simple"); StartManagers(); } } }); } catch { } }); }while (MainTaskSync.WaitOne(TimeSpan.FromSeconds(2)) == false); StopManagers(true); StopWebServer(); History.Add(HistoryItems.ServiceEnded); EventThread.ControlledStop(); Logger.Info <SactaProxy>("Servicio Detenido."); }
/// <summary> /// Checks if an event is queued for processing. /// </summary> /// <param name="nsfEvent">The event in queustion.</param> /// <returns>True if the event is the in queue, otherwise false.</returns> protected bool hasEvent(NSFEvent nsfEvent) { return(EventThread.hasEvent(nsfEvent)); }
public BufferSizeControl(long maxSize, Connection connectionControl, EventThread connectionThread) { _maxSize = maxSize; _connectionControl = connectionControl; _connectionThread = connectionThread; }
/// <summary> /// Checks if an event is queued for handling. /// </summary> /// <param name="nsfEvent">The event in queustion.</param> /// <returns>True if the event is the in queue, otherwise false.</returns> public bool hasEvent(NSFEvent nsfEvent) { return(EventThread.hasEvent(nsfEvent)); }
/// <summary> /// Checks if any events are queued for handling. /// </summary> /// <returns>True if there are events queued for handling, otherwise false.</returns> public bool hasEvent() { return(EventThread.hasEventFor(this)); }
/// <summary> /// Gets the thread time for a particular thread. /// </summary> /// <param name="thread">The thread to query.</param> /// <returns>The time elapsed in the frame in any state.</returns> public double GetOnCoreRatio(EventThread thread) { if (!this.OnCoreMap.ContainsKey(thread)) return 0; // Get the grand total of the time var total = this.OnCoreMap.Sum(t => t.Value); // Return the current on-core ratio. return this.OnCoreMap[thread] / total; }