Coroutine take extremely long time for simply calculation

Hello community,
i have created here some code for a simply test for something like a asynchron calculation. But i was realy surprised to see how much time a coroutine take to count to 1000? Nearly 17 seconds?! A simply while lop will take much fewer as 1ms for that. May be i do something wrong because i can not belive it is normal time for this operation.

Here is my code:

using UnityEngine;
using System.Linq;
using System.Diagnostics;
using System.Collections;

public class UnitTest : MonoBehaviour {
    delegate void OnCalculationResult(int result);
    void Start()
    {
        DoSomeStuff();
    }

    private void DoSomeStuff()
    {
        print("I do some stuff");
        //Calculate(100, HandleResult);
        StartCoroutine(Calculate(HandleResult));
        print("I do some another stuff [1]");
        print("I do some another stuff [2]");
        print("I do some another stuff [3]");
        print("I do some another stuff [x]");
    }

    private void HandleResult(int result)
    {
        print("Calculation result handled: " + result.ToString());
    }
    private IEnumerator Calculate(OnCalculationResult ResultHandleFunction)
    {
        Stopwatch watch = System.Diagnostics.Stopwatch.StartNew();

        var initValue = 0;
        while (initValue < 1000)
        {
            initValue++;
            yield return null;
        }
        watch.Stop();
        print("MyCoroutine is now finished in: " + watch.ElapsedMilliseconds.ToString() + " ms.");
        ResultHandleFunction(initValue);
    }
}

The result is: http://shot.qip.ru/00NDav-2oHGounG8/

Coroutines does not process things asynchronous (like a thread would do), they just span the process over frames (or time if you use WaitForSeconds).

In your case, each iteration has to wait 1 frame

yield return null;

So this time that you see it is the time that 1000 frames take in your game.

1 Like

Oh, now i see! Thank you. Now it make sense for me!

coroutine != thread

coroutine != thread

yes, i understand. The sense of this test was not to make a real asyncronous operation, but the code should go further and not wait for calculation end. My keyword asynchron is wrong in this case, i know.

My mistake was to put yield method inside the while loop. It should be on the first line inside Calculate IEnumerator. In this case it return one time wait for 1 frame and the code below will execute “callback” after it is completed. In this time the parent function where i started my coroutine can go further without waiting for a result.