UniTask v2 — Zero Allocation async/await for Unity, with Asynchronous LINQ

  • Callback process still remains
  • Can’t use try-catch-finally because of the yield syntax
  • Allocation of the lambda and the coroutine itself
  • Difficult to do cancellation process(coroutine only stop, not call dispose)
  • Impossible to control multiple coroutines (serial/parallel processing)
  • await support for each Unity’s AsyncOpeations
  • Unity’s PlayerLoop-based switching process (Yield, Delay, DelayFrame, etc…) allows for all the functionality of a coroutine on UniTask
  • await support for MonoBehaviour events and uGUI events
  • Zero-allocation of the entire async method to further improve performance
  • Asynchronous LINQ(UniTaskAsyncEnumerable, Channel, AsyncReactiveProperty)
  • Increased PlayerLoop timing (new LastPostLateUpdate will have the same effect as WaitForEndOfFrame)
  • Support for external assets such as Addressables and DOTween

Principle of AsyncStateMachine and Zero Allocation

While there are many new features, such as asynchronous stream support, the biggest feature of UniTask v2 is a significant performance improvement.

  • Task Allocation
  • Boxing the AsyncStateMachine
  • Allocation of the Runner encapsulating the AsyncStateMachine
  • Allocation of delegate for MoveNext

Coroutine and PlayerLoop

One of the key features of UniTask, which differs from Task, is to not use SynchronizationContext(and ExecutionContext) at all.

Asynchronous LINQ

With the introduction of C# 8.0 support in Unity 2020.2.0a12, asynchronous Stream is now possible. For example, the following statement replaces Update()!

Enhanced await support

In default, await support for AsyncOperation, ResourceRequest, AssetBundleRequest, AssetBundleCreateRequest, and UnityWebRequestAsyncOperation are all included in UniTask.

.NET Core

New from UniTask v2, the .NET Core version of UniTask is now available in NuGet. It has a higher performance than the standard Task/ValueTask, but it is not as easy to use as ignoring the ExecutionContext/SynchronizationContext.

Conclusion

It’s been two years since the release of the first UniTask, and while many games have adopted it, we’ve been able to there are still many people who don’t understand or misunderstand about async/await.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Yoshifumi Kawai

Yoshifumi Kawai

a.k.a. neuecc. Creator of UniRx, UniTask, MessagePack for C#, MagicOnion etc. Microsoft MVP for C#. CEO/CTO of Cysharp Inc. Live and work in Tokyo, Japan.