Search Unity

Assets Asyncoroutine - Use coroutine and async/await together

Discussion in 'Works In Progress - Archive' started by zsaladin, Sep 16, 2017.

  1. zsaladin

    zsaladin

    Joined:
    Jan 20, 2015
    Posts:
    11
    Asyncoroutine
    Asyncoroutine is a unity asset that allows you to use Coroutine and async/await together. You might face the situation that Coroutine and async/await get together. In this situation 'Asyncoroutine' is useful. You don't need to switch your code style from Coroutine to async/await or from async/await to Coroutine by using 'Asyncoroutine'. See below.

    How to use

    Coroutine in async/await
    You can 'await' Coroutine in async/await.
    Code (CSharp):
    1. using Asyncoroutine;
    2.  
    3. async void Awake()
    4. {
    5.    await new WaitForSeconds(1f);
    6.    Debug.Log("WaitForSeconds");
    7.  
    8.    await Task.Delay(1000);
    9.    Debug.Log("Delay");
    10.  
    11.    WWW www = await new WWW("http://google.com");
    12.    Debug.Log(www.text);
    13.  
    14.    await new WaitForSecondsRealtime(1f);
    15.    Debug.Log("WaitForSecondsRealtime");
    16.  
    17.    await UnityCoroutine();
    18.    Debug.Log("UnityCoroutine");
    19. }
    As you can see, you just write 'await' at the front of Coroutine or YieldInstrunction like WaitForSeconds. All the things will happen by 'using Asyncoroutine'.

    Also it makes 'Awake' and 'OnEnable' use Coroutine. Unlike 'Start' we could not use Coroutine in them but you can from now. (Actually there is an another alternative in above situation. See link)

    Moreover you can use Coroutine on 'OnDisable' by using it.

    Task in Coroutine
    If you don't familiar with async/await then use original Coroutine style with async/await
    Code (CSharp):
    1. using Asyncoroutine;
    2.  
    3. private IEnumerator Start()
    4. {
    5.     yield return new WaitForSeconds(1f);
    6.     Debug.Log("WaitForSeconds");
    7.  
    8.     yield return Task.Delay(1000).AsCoroutine();
    9.     Debug.Log("AsCoroutine1 Delay");
    10.  
    11.     var taskYieldInstruction = Task.Run(() => LongTimeJob()).AsCoroutine();
    12.     yield return taskYieldInstruction;
    13.  
    14.     Debug.LogFormat("AsCoroutine2 Task.Run Result : {0}", taskYieldInstruction.Result);
    15. }
    Just write 'AsCoroutine()' at the end of Task. It creates a proper YieldInstrunction which Coroutine can handle.

    Note : You must have Unity 2017 or above and be sure that Scripting Runtime Version is '.Net 4.6'.

    https://github.com/zsaladin/Asyncoroutine
     
    Last edited: Sep 16, 2017