Creating A Thread Class

As per my previous threading piece, I’m leaning into using the simpler .NET systems for threading, namely System.Thread and System.Threading.WaitHandle. The main difference here is that I want to kick off a thread and allow it to keep running for as long as the algorithm takes, rather than running a loop in lockstep with the Unity Update loop.

The ThreadWorker Class

Our first pass at this class is going to be very simple:

using System;
using System.Threading;

public class ThreadWorker
{
    private Thread ChildThread = null;

    public void Start(Action action)
    {
        ChildThread = new Thread(ThreadImpl);
        ChildThread.Start(action);
    }

    private void ThreadImpl(object action)
    {
        var impl = action as Action;
        impl();
        ChildThread = null;
    }

    public bool IsRunning() {return ChildThread != null;}
    public bool IsCompleted() {return ChildThread == null;}
}

So we can create a new ThreadWorker and give it a function to perform (passed in as an Action, then poll the IsRunning() or IsCompleted() functions each frame until it’s done, which might look something like the following:

using UnityEngine;

public class ThreadLauncher : MonoBehaviour
{
    private ThreadWorker Worker = null;
    void Start()
    {
        Worker = new ThreadWorker();
        Worker.Start(ExpensiveAlgorthim);
    }

    void Update()
    {
        if(Worker.IsCompleted())
        {
             // use results;
        }
    }

    private void ExpensiveAlgorthim()
    {
        // etc.
    }
}

NOTE: the tests for IsRunning() and IsComplete() are inherently threadsafe, because reference assignment and read are both atomic operations. Just remember that, in general, you don’t want to be accessing data from multiple threads without taking careful to guard those accesses.

Really, this is just a wrapper around System.Thread and doesn’t offer much in new functionality. So let’s look at pausing and resuming threads.

Pausing, Resuming and Aborting Threads

Return to Blog