Search Unity

A simple Unity Thread Dispatcher for use with async/await

Discussion in 'Scripting' started by Neonlyte, Dec 29, 2019.

  1. Neonlyte

    Neonlyte

    Joined:
    Oct 17, 2013
    Posts:
    515
    Hi all, I don't know if this would be anything useful to anyone, or if anyone is interested in reading my code, but I have written a Unity Thread Dispatcher as a companion tool for Async/Await code.

    It is proven to be very useful when you do things in an async method and callbacks from async operations, say network requests, and wish to update the game UI or store a variable in the PlayerPrefs, since all Unity API are assumed thread-unsafe and will throw exceptions if executing from a thread other than the "main thread".

    To use, simply call any Unity API (or any method you need to run on Unity thread, really) like so:
    Code (CSharp):
    1. // Discard the returned task to "run and forget", like dispatch_async in Objective-C
    2. _ = K4UnityThreadDispatcher.Execute(PlayerPrefs.SetFloat, "prefKey", (float)1);
    3.  
    4. // Wait for execution finishes and retrieve return values from any methods
    5. int i = await K4UnityThreadDispatcher.Execute(PlayerPrefs.GetInt, "prefKey", 1);
    6.  
    7. // You can also simply pass in a lambda expression, giving you limitless flexibility
    8. string persistentDataPath = await K4UnityThreadDispatcher.Execute(() => Application.persistentDataPath);
    9.  
    10. // Schedule an execution on any object instance
    11. await K4UnityThreadDispatcher.Execute(gameObject.SetActive, true);
    This does require .NET 4.X, but since old .NET is deprecated, I don't think it's a problem for most relatively new projects.

    The implementation does use lambda expressions extensively, if this concerns anyone. I personally have not experienced any performance impact.

    The code is on GitHub Gist:

    https://gist.github.com/heshuimu/f63cd9126117afc4004be37b19fa1c09
     
    wujinjindx, Zarkend and jbassking like this.