using System.Threading.Tasks;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
TestAsync();
}
async void TestAsync()
{
int i = 0;
while (true)
{
Debug.Log($"### TestAsync: {++i}");
await Task.Delay(1); // ok
// await Task.Delay(0); // hang!
// await Task.Yield(); // hang!
}
}
}
While posting this thread, I do notice that there is another thread talking about a similar issue: Help with async await
But regardless, the above code when attached to a scene will hang the whole Unity editor when using Task.Delay(0) and Task.Yield(), is this the expected behavior?
We have made one change due to this report however. Currently, when processing async/await continuations, we currently process the continuations that are spawned from existing continuations. This is why Task.Yield() would hang. Instead soon (once the changes land in 2018.1), if an āawaitedā function calls await again, that continuation will be processed on to the next pass through the player loop. I should mention that weāre also considering changes to where we process continuations in the playerloop (currently fixedupdate) since this behavior seems inconsistent in some ways with how other .NET implementations work.
I stumbled across this and did some digging (Unity 2019 LTS). It seems it moved to Update (evaluated once per frame). It is called between Update() and LateUpdate() and after coroutine āyield nullā.
Here is how the updated lifecycle graph would look like:
I am facing the new bug in Unity2021.3.0f1:
When I use await Task.Yield() in Editor, everything works fine, but after I build the game, it just āfreezeā on this line of code. Hereās the test code:
void Start()
{
Test();
}
async void Test()
{
Debug.LogError("Test Begin");
await Task.Yield();
Debug.LogError("Test End");//Will not be executed!
}