// Accepts new connection contexts private void AcceptContext() { // Create a wait handle array so we can cancel this thread if need be WaitHandle[] Wait = new[] { ReadyEvent, StopEvent }; while (0 == WaitHandle.WaitAny(Wait)) { // Lock our context queue to prevent race conditions lock (ContextQueue) { // Context queue has entries, accept one if (ContextQueue.Count > 0) { // Dequeue next context in line var Context = ContextQueue.Dequeue(); // Handle this context HandleRequest(Context); } // There are no entries in the connection queue else { // No context in line, reset ready event ReadyEvent.Reset(); continue; } } } }
/// <summary> /// Replaces the context in the core and saves the old one in the queue. /// </summary> /// <param name="core"> The core whose context had a context switch</param> private void SwapContext(Core core) { // If context queue is empty then keep running the same thread if (ContextQueue.Count > 0) { var newContext = ContextQueue.Dequeue(); var oldContext = core.Context; ContextQueue.Enqueue(oldContext); core.Context = newContext; core.ThereAreContexts = true; } core.RemainingThreadCycles = Quantum; // Restores remaining cycles to the quantum value. }
/// <summary> /// Picks off a context from the context queue. /// </summary> /// <returns> Thre next context of the queue or null if the queue is empty.</returns> private Context GetNewContext() { return ContextQueue.Count == 0 ? null : ContextQueue.Dequeue(); }