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: