Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by omercem94 · May 24, 2019 at 12:29 PM · coroutinecoroutinesasyncasynchronous

How to make functions async?

Hi everyone,

I have an expensive function that takes 3-4 seconds to complete. When I call this function inside of a script it, app freezes for 3-4 seconds till the result back. I have searched and seen async/await/task method. It says it is like javascript async/await but I coudn't make it work. Like in javascript can I make my expensive function async so that it works in the background without freezing my unity app? How can I make function async and wait result in coroutine yield return or await?

     public void ExpensiveFunction()
     {
        // Lots of operations.
     }

      IEnumerator MyCoroutine()
     {
             await MyResult = ExpensiveFunction();
     }
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

2 Replies

· Add your reply
  • Sort: 
avatar image
4

Answer by Pangamini · May 24, 2019 at 01:07 PM

You can start a pooled thread execution using BeginInvoke(). Then, wait for the result in a coroutine

 // this is a coroutine body
 {
      // concurrently run something
      System.Func<string> concurrentMethod = ExpensiveThreadedFunction;
      var concurrentResult = concurrentMethod.BeginInvoke(null, null);
      while (!concurrentResult.IsCompleted)
      {
               yield return Waits.waitForEndOfFrame;
      }
      string expensiveResult = concurrentMethod.EndInvoke(concurrentResult);
      Debug.Log(expensiveResult );
 }
 
 string ExpensiveThreadedFunction()
 {
     // do something that takes very long 
 }
 
 
Comment
Add comment · Show 10 · 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 Pangamini · May 24, 2019 at 01:10 PM 0
Share

You can wait any arbitrary amount of time in the loop, if you think it's expensive to check for operation completion every frame

avatar image dontdiedevelop · May 24, 2019 at 01:24 PM -1
Share

This way can't solve the app freeze issue because you're trying to cast all function and your waitforendofframe only wait for log not function :D he needs to seperate his function this is only way i know

avatar image Pangamini dontdiedevelop · May 24, 2019 at 01:26 PM 0
Share

Oh you misunderstand the concept, really. BeginInvoke will execute the deletage on another thread. Until the threaded execution is complete, the coroutine spins in the loop, leaving the app responsive. Afrer the threaded execution is complete, the return value is retrieved using EndInvoke, and the execution of the coroutine continues (on the main thread ofc)

avatar image dontdiedevelop · May 24, 2019 at 01:32 PM -1
Share

Dude, move the EXPENSIVE Function to another thread is not enough do you think another thread can handle it without freeze? You can't know that and he says he had 4-5 second freeze this mean is function is not expensive is SO EXPENSIVE

avatar image Pangamini dontdiedevelop · May 24, 2019 at 01:34 PM 2
Share

Please. Yes, that's exactly why it won't freeze. Because it runs concurrently on another thread. Just because you don't know the soludiuon, you don't have to imply that it doesn't exist. I've copied this code (and renamed the methods) from my production code where I am generating super long JSONs, exactly for the purpose of NOT freezing the main engine loop.

avatar image dontdiedevelop Pangamini · May 24, 2019 at 01:42 PM -1
Share

okay let's try this situations with expensive function and we can try my solution on main thread it's will be faster you will see:)

Show more comments
avatar image omercem94 · May 29, 2019 at 08:01 AM 0
Share

Sorry for late response I have been busy with another task. I will try your solution asap. Thank you!

avatar image Pangamini omercem94 · May 29, 2019 at 08:33 AM 0
Share

Np. Of course, your expensive operation must be executable on another thread. If it depends on some scene data, texture data or something, you should collect that in the coroutine (or somewhere else on the main thread) and just run the computation that doesn't break unity rules about threaded access

avatar image Pangamini omercem94 · Jun 11, 2019 at 12:52 PM 0
Share

Did it work for you?

avatar image
-2

Answer by dontdiedevelop · May 24, 2019 at 12:40 PM

      IEnumerator ExpensiveFunction()
      {
              operation1();
              yield return new WaitForSeconds(0.4f);
              operation2();
      }

Comment
Add comment · Show 3 · 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 omercem94 · May 24, 2019 at 01:03 PM 0
Share

As far as I understood you suggest me to break my expensive function into smaller operations and call yield return after each of them right? Problem is that is very large function and some operations are hard to break into smaller parts.

avatar image dontdiedevelop · May 24, 2019 at 01:05 PM 0
Share

async functions works like this you can use it or not your choice

avatar image PixxlMan dontdiedevelop · May 24, 2019 at 01:56 PM 1
Share

Not at all. You could do it in multiple ways. I would recommend a separate thread for executing this, or even better @Panga$$anonymous$$i ´s solution.

The IEnumerator will simply work in the same fram until it is done, and will do you no good, unless ExpensiveFunction can be spread out over multiple frames and then you just make Expensive function into a coroutine, and wait for a frame between every major operation.

@omercem94

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

118 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 avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Can you run a coroutine more often than Update? 1 Answer

How to load scene when async.progress is 0.9? 0 Answers

How to properly implement a constant queue of actions in the background,How to properly implement a continuous background queue of actions? 1 Answer

StartCoroutine and Yield 0 Answers

Async parse.com query not working on Android/iOS 2 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