• 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
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 bW$$anonymous$$leTrue = true;
 
     void Start(){
         func();
     }
 
     void func(){
         Task task = longRunning();
         w$$anonymous$$le(bW$$anonymous$$leTrue){
             Debug.Log("func: In W$$anonymous$$leTrue loop");
         }
         Debug.Log("func: After w$$anonymous$$leTrue loop");
     }
         
     async Task longRunning(){
         await Task.Delay(3000);
         Debug.Log("Async: After delay");
         bW$$anonymous$$leTrue = false;
     }
 }

What I expect is that
1) from Start(), func() will be called
2) In func(), the (async) longRunning() function is called
3) longRunning() $$anonymous$$ts the await line, and returns to func(), its caller, w$$anonymous$$le the Task.Delay(3000) is performed asynchronusly.
4) func() enters the infinite loop, and keeps looping because the bW$$anonymous$$leTrue is true, printing "func: In w$$anonymous$$leTrue loop"
5) Eventually, Task.Delay(3000) finishes, and the rest of the longRunning() is performed so that bW$$anonymous$$leTrue is set to false.
6) Since bW$$anonymous$$leTrue is set to false, func() can exit the infinite w$$anonymous$$le loop, and prints "func: After w$$anonymous$$leTrue 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 t$$anonymous$$nk, the Editor should not hang for longer than 3 seconds at maximum. Sorry if I miss anyt$$anonymous$$ng 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, t$$anonymous$$s code works fine for C# console application:

 using System;
 using System.Threading.Tasks;
 
 namespace TestAsync {
     class Program {
         static bool bW$$anonymous$$leTrue = true;
 
         static void Main(string[] args) {
             func();
         }
 
         static void func(){
             Task task = longRunning();
             w$$anonymous$$le(bW$$anonymous$$leTrue) {
                 Console.WriteLine("func: In W$$anonymous$$leTrue loop");
             }
             Console.WriteLine("func: After w$$anonymous$$leTrue loop");
         }
         
         static async Task longRunning(){
             await Task.Delay(3000);
             Console.WriteLine("Async: After delay");
             bW$$anonymous$$leTrue = false;
         }
     }
 }
Comment

People who like this

0 Show 0
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
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 w$$anonymous$$ch schedules tasks on the main thread, just like coroutines. Otherwise you couldn't interact with the UnityAPI from wit$$anonymous$$n 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 w$$anonymous$$ch does not happen in Unity. Here's a rather up-to-date blog about Unity and async / await.

Comment
Llama_w_2Ls
Fadi_sam

People who like this

2 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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

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

Creating a fade out and in transition for loading. Functions not executing in order. 1 Answer

Async parse.com query not working on Android/iOS 2 Answers

Instantiate fails with no errors 0 Answers

Take screenshot and use it as texture using ScreenCapture 2 Answers

AsyncOperation activating immediately even with async.allowSceneActivation = false; 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