Skip to main content

Async Await

Asynchronous programming is very popular with the help of the async and await keywords in C#. And Luna supports those! Below are some verified samples.

  1. Parallel calls
//parralel calls
async Task DoWorkParallel()
{
Debug.Log( "parralel calls" );
TickParallel();
TockParallel();
}
//Task method will work but not if you are not about to wait for it keep it void
async Task TickParallel()
{
Debug.Log( "Parallel Tick Waiting 0.5f second..." );
await Task.Delay( TimeSpan.FromSeconds( 0.5f ) );
Debug.Log( "Parallel Tick Done!" );
}
//void as return value
async void TockParallel()
{
Debug.Log( "Parallel Tock Waiting 0.5f second..." );
await Task.Delay( TimeSpan.FromSeconds( 0.5f ) );
Debug.Log( "Parallel Tock Done!" );
}
  1. Sequential calls
//sequential calls
//calling method have to be marked as async

async Task DoWorkSequential()
{
Debug.Log( "sequential calls" );
await TickSequential();
await TockSequential();
}
//void method
async Task TickSequential()
{
Debug.Log( "Sequential Tick Waiting 1 second..." );
await Task.Delay( TimeSpan.FromSeconds( 1 ) );
Debug.Log( "Sequential Tick Done!" );
}
//In order to wait for result return value should be Task
async Task TockSequential()
{
Debug.Log( "Sequential Tock Waiting 1 second..." );
await Task.Delay( TimeSpan.FromSeconds( 1 ) );
Debug.Log( "Sequential Tock Done!" );
}
  1. Getting data from task (using Task<T>)
Debug.Log( await TickTockTracker() );
//getting come data out of task
async Task<string> TickTockTracker()
{
return "Return result sample";
}

4.Custom Awaiter

//call for it
await CustomAwaiter();
//extenstion for TimeSpan
public static class AwaitExtensions
{
public static TaskAwaiter GetAwaiter( this TimeSpan timeSpan )
{
return Task.Delay( timeSpan ).GetAwaiter();
}
}
  1. Calling from Coroutine
StartCoroutine( RunTask() );
IEnumerator RunTask()
{
yield return RunTaskAsync().AsIEnumerator();
}
async Task RunTaskAsync()
{
Debug.Log( "RunTaskAsync Start" );
await TimeSpan.FromSeconds( 1 );
Debug.Log( "RunTaskAsync Finish" );
}
public static class AwaitExtensions
{
public static IEnumerator AsIEnumerator( this Task task )
{
while ( !task.IsCompleted )
{
yield return null;
}
if ( task.IsFaulted )
{
throw task.Exception;
}
}
  1. Use of async for Unity callbacks
async void Start()
{
await DoWorkParallel();
await DoWorkSequential();
Debug.Log( await TickTockTracker() );
await CustomAwaiter();
StartCoroutine( RunTask() );
}