Monday, May 25, 2015

Unity: Creating a C# Thread with Callback Argument

Sometimes we need to do processing in a different thread other then Unity Ui Thread. In Unity everything is handled in Ui thread; however you can of course create other treads.

The tricky part here is; when non ui thread completes it's job; it should trigger the "callback method" called by Ui thread instead of calling it self directly. (Otherwise Unity would complain that you were trying to access unity libs from a non ui thread and you would also break single thread mechanism.)

In the following code you can see that,  DoJobAsync is called from Ui thread; and we pass a JobResultHandler which should be called from Ui thread when the non-ui thread finishes it's job.
In #6 you see that we only create a ThreadAdapter if there is a callback parameter to prevent object creation cost. Of course this can be improved by object pooling etc. ThreadAdapter ia created in Ui thread since it is an Unity game object.

After ThreadAdapter is created; in every frame/in x seconds (it's your decision); it checks a volatile variable named waitCall.  waitCall is set to false from non-ui thread when it completes it's job in #25.

I think the code is more clear :). Please see it below:


  1. keep up the good work. this is an Assam post. this to helpful, i have reading here all post. i am impressed. thank you. this is our digital marketing training center. This is an online certificate course
    digital marketing training in bangalore /

  2. You have provided finicky information for a new blogger so it has turned out to be really obliging. Keep up the good work!
    Data Science training in Mumbai
    Data Science course in Mumbai
    SAP training in Mumbai

  3. wonderful article contains lot of valuable information. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.
    This article resolved my all queries.good luck an best wishes to the team members.continue posting.learn digital marketing use these following link
    Digital Marketing Course in Chennai