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
};

_backgroundWorker.RunWorkerAsync(argumetToPassOrNull);

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

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

wolf
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

Ilya
Posted on 11/24/2017 7:57:20 AM

Hi. Cool solution. But how can I work with functions or corutines that should start with main thread? I really want to work with the REST api in the background (when the application is minimized), and under certain circumstances show pop up even if the application is minimized. could you please advise something?

Vladimir Bodurov
Posted on 11/24/2017 10:33:07 AM

This solution is only for operations that does not require to work on the main threads, otherwise you should just use coroutines, they run on the main thread,

Please post your comments:

Name:  
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: