If you need to execute some long running task on the background in Unity, you may find this tool I just wrote, useful. This is BackgroundWorker for Unity 3D

BackGround Worker for Unity3D

You will only need the class BackgroundWorker

It worth noting that a lot of seemingly background tasks can be implemented with Unity Coroutines. For example using WWW service to send or receive data from a remote server. Or any case where we just wait for a response from a remote computer.

However because coroutines run on the main thread if you really have a long running, not just waiting for response but computing intensely something, you will need to run it on a background thread. Here is how you use this tool:

if (_backgroundWorker != null) _backgroundWorker.CancelAsync();
_backgroundWorker = new BackgroundWorker();

_backgroundWorker.DoWork += (o, a) =>
    // executed on background thread
    // do slow running computationaly intense work, check periodically 
    // if (a.IsCanceled) return;
    // assign result as 
    // a.Result = a.Argument+"!";
_backgroundWorker.RunWorkerCompleted += (o, a) =>
    // executed on main thread
    // you can use a.Result


And then on each frame execute:

if (_backgroundWorker != null) _backgroundWorker.Update();

The tool has been tested on Windows, Mac, iPhone, and Android.

This is a sample usage of the BackgroundWorker class.

Share this post:   digg     Stumble Upon     del.icio.us     E-mail

Posted on 10/28/2014 4:38:32 PM

So would this runs on iOS?

Vladimir Bodurov
Posted on 10/29/2014 2:36:18 AM

Yea, try the sample project.

Posted on 11/13/2017 8:58:00 AM

Is this code still running even when the app looses its focus?

Vladimir Bodurov
Posted on 11/13/2017 12:06:20 PM

Focus cannot have effect on that

Please post your comments:

Email (optional): Your email address will not be posted.
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box: