Awaitable code example reference
Solve common asynchronous programming problems with a reference of Awaitable code examples.
Read time 3 minutesLast updated 13 days ago
The examples in this reference demonstrate solutions to common scenarios encountered when writing asynchronous code.
AwaitableAsynchronous tests
Unity's Test Framework doesn't recognize as a valid test return type. However, the following example shows how you can use the implementation of to write async tests:
AwaitableAwaitableIEnumerator[UnityTest]public IEnumerator SomeAsyncTest(){ async Awaitable TestImplementation(){ // test something with async / await support here }; return TestImplementation();}
Frame coroutines
You can use the frame-related async methods in the class to create asynchronous Unity coroutines as an alternative to iterator-based coroutines:
Awaitableasync Awaitable SampleSchedulingJobsForNextFrame(){ // Wait until end of frame to avoid competing over resources with other Unity subsystems await Awaitable.EndOfFrameAsync(); var jobHandle = ScheduleSomethingWithJobSystem(); // Let the job execute while the next frame starts await Awaitable.NextFrameAsync(); jobHandle.Complete(); // Use results of computation}JobHandle ScheduleSomethingWithJobSystem(){ ...}
Conditional wait
In iterator-based coroutines, WaitUntil suspends a coroutine execution until a delegate evaluates . You can create equivalent behavior for an -returning asynchronous method by making it wait until a condition changes using a cancellation token:
trueAwaitablepublic static async Awaitable AwaitableUntil(Func<bool> condition, CancellationToken cancellationToken){ while(!condition()){ cancellationToken.ThrowIfCancellationRequested(); await Awaitable.NextFrameAsync(); }}
You can then pass in a cancellation token as follows:
cancellationTokenSource = new CancellationTokenSource();currentTask = AwaitableUntil(myCondition, cancellationTokenSource.Token);
Loading resources asynchronously
You can an asynchronous resource loading operation so that it doesn't block the main thread:
awaitpublic async Awaitable LoadResourcesAsync(){ // Load texture resource asynchronously var operation = Resources.LoadAsync("my-texture"); // Return control to the main thread while the resource loads await operation; var texture = operation.asset as Texture2D;}
Composition
You can multiple different -compatible types in the same method:
awaitawaitpublic async Awaitable Bar(){ await CallSomeThirdPartyAPIReturningDotnetTask(); await Awaitable.NextFrameAsync(); await SceneManager.LoadSceneAsync("my-scene"); await SomeUserCodeReturningAwaitable(); ...}
Wrapping Awaitable in .NET Task
To work around some of the limitations of you can wrap it in a .NET . This incurs the cost of an allocation but gives you access to methods such as and from the API. To do this you can write your own custom extension methods as follows:
AwaitableTaskWhenAllWhenAnyTaskAsTask// Implement custom AsTask extension methods to wrap Awaitable in Taskpublic static class AwaitableExtensions { public static async Task AsTask(this Awaitable a) { await a; } public static async Task<T> AsTask<T>(this Awaitable<T> a) { return await a; } }
Await a result multiple times
A major difference between and is that objects are pooled to reduce allocations. You can't safely an -returning method that completes with a result multiple times because once returned the original object is returned to the pool.
AwaitableTaskAwaitableawaitAwaitableAwaitableUnsafe version
The following code is not safe and will lead to exceptions and deadlocks:
async Awaitable Bar(){ var taskWithResult = SomeAwaitableReturningFunction(); var awaitOnce = await taskWithResult; // Do something // The following will cause errors because at this point taskWithResult has already been pooled back var awaitTwice = await taskWithResult; }
Safe version
This is one of the scenarios where you can wrap Awaitable in a Task at the cost of an allocation. The can then be safely awaited multiple times:
Task// Implement custom AsTask extension methods to wrap Awaitable in Taskpublic static class AwaitableExtensions { public static async Task AsTask(this Awaitable a) { await a; } public static async Task<T> AsTask<T>(this Awaitable<T> a) { return await a; } }async Awaitable Bar(){ var taskWithResult = SomeAwaitableReturningFunction(); // Wrap the returned Awaitable in a Task var taskWithResultAsTask = taskWithResult.AsTask(); // The task can now be safely awaited multiple times, at the cost of allocating var awaitOnce = await taskWithResultAsTask; // Do something var awaitTwice = await taskWithResultAsTask; }