How to prevent heavy method calculation from locking Unity up?

Hello, everyone!

Right now Im having an issue with a method, called from a DLL, in which it can take a long time before this method finishes its calculation and in the mean time I simply cannot use anything on Unity.

I tried using a thread (see below) so that Unity could continue its tasks while my method calculation was being done, but that didnt work out.

 IntPtr resultPointer = default(IntPtr);
            Debug.Log( "Startin thread... " );
            System.Threading.Thread thread = new System.Threading.Thread(
                () =>
                {
                    resultPointer = computeMinBox3D( _pointsFloatVector.Length, _pointsFloatVector, 8 );
                }
                );
            thread.Start( );
            thread.Join( );
            Debug.Log( "Thread work done!" );

I read some of the coroutine documentation and figured it wouldnt solve my problem either.

My second try is the following:

private IEnumerator YieldComputeMinBox3D( int pointsFloatVectorLength, float[] pointsFloatVector, int numThread )
        {
            _resultPointer = computeMinBox3D( pointsFloatVectorLength, pointsFloatVector, numThread );

            yield return null;
        }

Altough this one does prevent Unity from locking up it also doesnt execute the method correctly, it seems to just skip its heavy calculation completely and doesnt continue where it is supposed to. What am I missing here?

Extra question: The method Im calling is already multithreaded. Would this be a problem?

In your thread version you’re calling thread.Join. This waits for the thread complete, which defeats the purpose.

You need to start the thread and let it run in parallel. At some point, possibly multiple frames in the future, that thread will complete its work and you can grab the result. You’ll need a way to communicate back to the main thread that the thread is complete. Then you get into synchronization issues and such which are beyond the scope here.

.NET has Tasks that would make this a bit easier, but I don’t think the version of Mono that Unity uses has those? Not 100% sure about that though.

Your only other option is to manually split the work across multiple frames, with coroutines or something, but that doesn’t seem very feasible unless the dll is yours and you can modify it.