3
private void RunEveryTenFrames(Color32[] pixels, int width, int height)
    {
        var thread = new Thread(() =>
        {
            Perform super = new HeavyOperation();
            if (super != null)
            {
                Debug.Log("Result: " + super);
                ResultHandler.handle(super);
            }
        });
        thread.Start();
    }

I'm running this function every 10 frames in Unity. Is this a bad idea. Also, when I try to add thread.Abort() inside the thread, it says thread is not defined and can't use local variable before it's defined error.

Faizuddin Mohammed
  • 4,118
  • 5
  • 27
  • 51

1 Answers1

2

Is it a good idea to create a new thread every 10 frames in Unity?

No. 10 frames is too small for repeatedly creating new Thread.

Creating new Thread will cause overhead each time. It's not bad when done once in a while. It is when done every 10 frames. Remember this is not every 10 seconds. It is every 10 frames.

Use ThreadPool. By using ThreadPool with ThreadPool.QueueUserWorkItem, you are re-using Thread that already exist in the System in instead of creating new ones each time.

Your new RunEveryTenFrames function with ThreadPool should look something like this:

private void RunEveryTenFrames(Color32[] pixels, int width, int height)
{
    //Prepare parameter to send to the ThreadPool
    Data data = new Data();
    data.pixels = pixels;
    data.width = width;
    data.height = height;

    ThreadPool.QueueUserWorkItem(new WaitCallback(ExtractFile), data);
}

private void ExtractFile(object a)
{
    //Retrive the parameters
    Data data = (Data)a;

    Perform super = new HeavyOperation();
    if (super != null)
    {
        Debug.Log("Result: " + super);
        ResultHandler.handle(super);
    }
}

public struct Data
{
    public Color32[] pixels;
    public int width;
    public int height;
}

I you ever need to call into Unity's API or use Unity's API from this Thread, see my other post or how to do that.

Programmer
  • 121,791
  • 22
  • 236
  • 328
  • 1
    Yes, you can also use Task but it is only supported in recent Unity 2017 release. Won't work on versions under that. – Programmer Feb 22 '18 at 12:58
  • You don't need to. – Faizuddin Mohammed Feb 22 '18 at 13:06
  • 1
    No. ThreadPool is basically a wrapper again Threads and will manage Threads or you. It will create a Thread if one do not exist yet and then re-use them each time you call that function again. You may want to use `ThreadPool.SetMaxThreads` to set limit on the Thread amount so that it doesn't go cuckoo on mobile devices. – Programmer Feb 22 '18 at 13:07