private IEnumerator MainThreadWaiting(LiteTask task, float promptInterval = 0.5f) { var nextPromptTime = 0f; do { var now = Time.realtimeSinceStartup; if (now > nextPromptTime) { nextPromptTime = now + promptInterval; Debug.Log("Main thread waiting..."); } yield return(null); }while (!task.IsDone); Debug.Log("Main thread caught task finished"); }
private IEnumerator Start() { mainThread = Thread.CurrentThread; // LiteTask allow you to run heavy script in background thread without blocking Unity main thread Debug.Log("### LiteTask in Background Thread"); var task = new LiteTask(HeavyTask()); StartCoroutine(task); yield return(MainThreadWaiting(task)); // LiteTask also works with LiteCoroutine as well Debug.Log("### LiteTask in Background Thread with LiteCoroutine"); task = new LiteTask(SleepTask()); var handle = LiteCoroutine.StartCoroutine(task); yield return(MainThreadWaiting(task)); // Stop/Cancel LiteTask Debug.Log("### Cancelling LiteTask"); task = new LiteTask(HeavyTask()); LiteCoroutine.StartCoroutine(ref handle, task); yield return(new WaitForSecondsUnscaledTime(2.5f)); task.Cancel(); yield return(task.Wait()); Debug.Log("Background task is cancelled"); // Restart & Reuse LiteTask Debug.Log("### Restarting LiteTask"); task = new LiteTask(HeavyTask()); LiteCoroutine.StartCoroutine(ref handle, task); yield return(new WaitForSecondsUnscaledTime(1.5f)); try { task.RestartTask(HeavyTask()); } catch (Exception e) { Debug.LogException(e); Debug.Log("Can't restart new task when task isn't done yet!"); } yield return(task.Wait()); Debug.Log("Must restart new task after task is done..."); yield return(LiteCoroutine.StartCoroutine(ref handle, task.RestartTask(SleepTask()))); // Exception in background thread Debug.Log("### Invalid Operation in Background Thread"); yield return(LiteCoroutine.StartCoroutine(ref handle, task.RestartTask(InvalidOperationInBackground()))); // Jump between Main & Background thread Debug.Log("### Jump Between Main & Background Thread"); yield return(LiteCoroutine.StartCoroutine(ref handle, task.RestartTask(JumpToMainThread()))); // Nested background task Debug.Log("### Nested Background Task"); yield return(LiteCoroutine.StartCoroutine(ref handle, task.RestartTask(NestedTasks()))); // tobackground can interrupt // jump only works in LiteTask // nested background task // pool }