Best way to run a long algorithm in the background?
Hi, I have a pathfinding algorithm and it takes so much time to run. It is a function that returns a node list. I tried coroutines and threads but I couldn't make it work properly. I just want to make it work in the background when I call it
start_process_in_the_background
Path = GetPath();
finish_background_process
I can start a thread in the background but I couldn't abort it when the algorithm finishes. I tried coroutines but they freeze the game during the algorithm. To sum up, what is the best way to call a function in the background?
Answer by insominx · Nov 06, 2015 at 09:08 PM
The only way to truly run something in the background is with a separate thread. Unfortunately the behavior of abort has not been something you can consistently rely upon for every platform (YMMV). You'll need to use a bool variable to signal the thread when it should finish. Something like:
// inside thread function
while (myThreadEnabled) {
// ... do stuff
}
// outside thread function
myThreadEnabled = false; // tell thread to finish
Once the thread function was exited naturally, it will terminate.
I used this but when I close the game Unity freezes since the thread still runs in the background. If you don't abort the thread, it is always a problem.
You may need to do a thread join on exit. In my code I have something like this:
void OnApplicationQuit() {
if (externalThread!= null) {
shouldExitThread= true;
// Give the thread a brief moment to complete
Thread.Sleep(100);
externalThread.Join();
externalThread= null;
}
}
Your answer
Follow this Question
Related Questions
Why Is This Coroutine Freezing my Unity5 editor? 2 Answers
Heavy use of Unity API & UI Thread 0 Answers
Infinite loop with named pipes 1 Answer