/// <summary> /// Only call this method from the main thread. /// </summary> public void ProcessMessageQueue() { AsyncPathResult result = null; // Lock the output queue lock (outgoing) { // Update the flag isMessageQueueEmpty = (outgoing.Count == 0); // Get the result if (outgoing.Count > 0) { result = outgoing.Dequeue(); } } if (result != null) { // Process the result result.invokeCallback(); } }
private void ThreadMain() { // Set the flag isRunning = true; // Used to calcualte the average Stopwatch timer = new Stopwatch(); try { // Loop forever while (isRunning == true) { // Get a request AsyncPathRequest request = null; // Lock the input queue lock (incoming) { // Calcualte the current thread load CalcualteLoad(); // Get a request if (incoming.Count > 0) { request = incoming.Dequeue(); } } // Check for a request if (request == null) { idleFrames++; // Take a long sleep - no load Thread.Sleep((int)targetTime); continue; } // Reset the idle frames idleFrames = 0; // Begin timing timer.Reset(); timer.Start(); // Lock the grid while we search lock (request.Grid) { // Execute the request request.Grid.FindPath(request.Start, request.End, request.Diagonal, request.Traversal2D, (Path path, PathRequestStatus status) => { // Create a result AsyncPathResult result = new AsyncPathResult(request, path, status); // Push the result to the outgoing queue lock (outgoing) { // Add result outgoing.Enqueue(result); } }); } // Stop timing and calculate the average time timer.Stop(); CalculateAverageTime(timer.ElapsedMilliseconds); // Calculate the amount of rest time based on the thread load int sleepDuration = (int)((1 - threadLoad) * targetTime); // Sleep based on the current thread load Thread.Sleep(sleepDuration); } // End while } catch (System.Exception e) { UnityEngine.Debug.Log(e); } }