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?

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.