Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by reevthechameleon · Jan 21, 2021 at 02:45 AM · loopasyncasynchronous

Async/Await function hangs when caller has infinite loop

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
1) from Start(), func() will be called
2) In func(), the (async) longRunning() function is called
3) longRunning() hits the await line, and returns to func(), its caller, while the Task.Delay(3000) is performed asynchronusly.
4) func() enters the infinite loop, and keeps looping because the bWhileTrue is true, printing "func: In whileTrue loop"
5) Eventually, Task.Delay(3000) finishes, and the rest of the longRunning() is performed so that bWhileTrue is set to false.
6) Since bWhileTrue is set to false, func() can exit the infinite while loop, and prints "func: After whileTrue loop"
7) 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;
         }
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Bunny83 · Jan 21, 2021 at 06:41 PM

Tasks do not necessarily run on a seperate thread. The default synchronisation context in plain C# / .NET uses a threadpool to run the tasks. However Unity uses it's own context which schedules tasks on the main thread, just like coroutines. Otherwise you couldn't interact with the UnityAPI from within your Task as it's not thread safe. Therefore your task does never finish because you block the main thread and you never return the control to Unity so it can never schedule your task. Your example requires that the task runs on a seperate thread which does not happen in Unity. Here's a rather up-to-date blog about Unity and async / await.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image reevthechameleon · Jan 22, 2021 at 02:51 AM 0
Share

I see. Thanks for the answer. As per your answer, I have adjusted the code in func() so that it can return control back to Unity:

 async void func(){
     Task task = longRunning();
     while(bWhileTrue){
         Debug.Log("func: In WhileTrue loop");
         await Task.Yield();
     }
     Debug.Log("func: After whileTrue loop");
 }

And now it runs fine.
Thanks for the link too! Will check it out in detail later.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

112 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to make functions async? 2 Answers

Asynchronous Level Load Progress on iPhone 1 Answer

StartCoroutine and Yield 0 Answers

await creates error with StreamReader 1 Answer

Two async operations at the same time not working ? why ? 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges