I have a slow level generation algorithm that freezes the main thread when it runs. I found this post which is exactly the same problem, but predates the Jobs system.
All the jobs examples I found are good for parallelizing a bunch of instances of some function but the JobHandle.Complete() still pauses the main loop until they are done. Is there a way to offload a function that will take several frames to complete with Jobs?
Or am I better off creating a thread manually as suggested in that other post?
Thanks
Edit
In response to DMGregory's comment, I see I don't need to call Complete() for it to run.
This code seems to work, is it safe?
public class JobTest : MonoBehaviour
{
JobHandle myJob;
bool started = false;
bool done = false;
void Update()
{
if (!started)
{
if (Time.realtimeSinceStartup > 5)
{
print("scheduling");
myJob = scheduleLongJob();
JobHandle.ScheduleBatchedJobs();
started = true;
}
}
if (myJob.IsCompleted && started)
{
print("job completed");
done = true;
}
}
JobHandle scheduleLongJob()
{
LongJob myJob = new LongJob();
return myJob.Schedule();
}
}
public struct LongJob : IJob
{
public void Execute()
{
float u = 0;
for (int i = 0; i < 50000000; i++)
{
u += math.exp10(math.sqrt(10f));
}
Debug.Log(u);
}
}