I have read that Unity now supports the async/await feature of the C# language, so I try writing some script and attach it to the GameObject in the scene:
using UnityEngine;
using System.Threading.Tasks;
public class TestAsync : MonoBehaviour{
bool bWhileTrue = true;
void Start(){
func();
}
void func(){
Task task = longRunning();
while(bWhileTrue){
Debug.Log("func: In WhileTrue loop");
}
Debug.Log("func: After whileTrue loop");
}
async Task longRunning(){
await Task.Delay(3000);
Debug.Log("Async: After delay");
bWhileTrue = false;
}
}
What I expect is that
- from Start(), func() will be called
- In func(), the (async) longRunning() function is called
- longRunning() hits the await line, and returns to func(), its caller, while the Task.Delay(3000) is performed asynchronusly.
- func() enters the infinite loop, and keeps looping because the bWhileTrue is true, printing “func: In whileTrue loop”
- Eventually, Task.Delay(3000) finishes, and the rest of the longRunning() is performed so that bWhileTrue is set to false.
- Since bWhileTrue is set to false, func() can exit the infinite while loop, and prints “func: After whileTrue loop”
- func() returns to Start(), and Start() complete
But when press play, the Editor hangs instead.
I am not sure what I misunderstand because if it is what I think, the Editor should not hang for longer than 3 seconds at maximum. Sorry if I miss anything basic, and that the code seems theoretical, but I am not very familiar with asynchronus programming and want to test how it works in Unity.
As a comparison, this code works fine for C# console application:
using System;
using System.Threading.Tasks;
namespace TestAsync {
class Program {
static bool bWhileTrue = true;
static void Main(string[] args) {
func();
}
static void func(){
Task task = longRunning();
while(bWhileTrue) {
Console.WriteLine("func: In WhileTrue loop");
}
Console.WriteLine("func: After whileTrue loop");
}
static async Task longRunning(){
await Task.Delay(3000);
Console.WriteLine("Async: After delay");
bWhileTrue = false;
}
}
}