public void RunThread(object n) { int number = (int)n; Debug.Log("Started pathfinding thread #" + number); secondWatch.Start(); while (Run) { try { if (secondWatch.ElapsedMilliseconds >= 1000) { secondWatch.Reset(); secondWatch.Start(); AproximateWork = Mathf.Clamp01(TimeThisSecond / 1000f); TimeThisSecond = 0; } int count = Queue.Count; if (count == 0) { Thread.Sleep(IDLE_SLEEP); } else { // Lock to prevent simultaneous read and write. PathfindingRequest request; lock (manager.QueueLock) { request = Queue.Dequeue(); } if (request == null) { // Very ocassionally happens. Nothing to worry about :) continue; } if (request.ReturnEvent == null) { // Object that requested it has been destroyed. No need to calculate path. continue; } List <PNode> l; watch.Reset(); watch.Start(); var result = Pathfinder.Run(request.StartX, request.StartY, request.EndX, request.EndY, manager.Provider, request.ExistingList, out l); watch.Stop(); LatestTime = watch.ElapsedMilliseconds; TimeThisSecond += LatestTime; // Got the results, now enqueue them to be given back to the main thread. The method automatically locks. manager.AddResponse(new PathReturn() { Callback = request.ReturnEvent, Path = l, Result = result }); } } catch (Exception e) { Debug.Log("Exception in pathfinding thread #" + number + "! Execution on this thread will attempt to continue as normal. See:"); Debug.LogError(e); } } secondWatch.Stop(); Debug.Log("Stopped pathfinding thread #" + number); }