Scene disappear and reappear on Microsoft Hololens app due to complex operations

Viewed 147

I developed an app for Microsoft Hololens in Unity, but when I try to do some complex operations (e.g. download data from a remote server, deserialize a json or build a gameObject at runtime), the scene on my Hololens disappears for few seconds and reappears when all operations are finished. This problem is not negligible, but I don't know how to optimize the app. I want to do these operations in a background thread, in order to not affect the main thread.

I can't exec some functions in a background thread, so I need a sort of "dispatcher" that Unity does not support to call them in main thread while I run the background thread, sleep it and return to exec it only when the dispatcher ended.

I tried to use Threads/Tasks, but I failed to build the app because Thread/Task classes are not found (maybe Hololens does not support them?).

With Threads or Tasks I tried to use Monitor.Wait() and Monitor.Pulse() to sync operations, but it seems that, when I use Monitor.Wait() on a secondary thread, puts to sleep the main thread, and the app does not respond until it'll receive a Monitor.Pulse() that will never arrive.

I tried to use some codes found on Internet to do a dispatcher (I have not a dispatcher in Unity) to call main functions on a secondary thread, but they put these functions at the bottom of a queue and I need to call them instantly.

(https://github.com/PimDeWitte/UnityMainThreadDispatcher)

(https://www.youtube.com/watch?v=k5mbg5kVveU)

I also tried to use coroutines on main thread and to use a lot of "yield return", but it was ineffective.

This is the general structure of my code:

IEnumerator GetData() {
    try {
        // Get data from a remote database
        CallTask();
        yield return null;
    }
    catch (Exception e) { Network error }
}

void CallTask() {
    Task t = new Task( () => BackgroundTask() );
    t.Start();
    t.Wait();
    // Do stuff when "FunctionThatHaveToBeCalledInMainThread()" has ended
}

void BackgroundTask() {
    // Do stuff
    FunctionThatHaveToBeCalledInMainThread();
    // Do stuff when "FunctionThatHaveToBeCalledInMainThread()" has ended
}
0 Answers
Related