Ending a Thread when ending the game

I just created a new thread from within my game.
I’m doing it the way I’m used to it in C#

myThread = new Thread(new ThreadStart(myManager.Process));
myThread.Start();

Which works fine so far. Unfortunately I realized after stopping the game in the Editor this thread keeps running.
Of course I can’t check something like EditorApplication.isPaused from within this thread. So how can I end it? It makes Unity not responding the moment I start the game again.
Is there any way to do some multi threading (i.e. not using StartCoroutine)?

Thanks!

Well, I don’t necessarily know how to kill a process, BUT! You can have an object in your scene that has its OnDestroy defined, which would contain the logic for killing the thread if it’s running. Then have this object DontDestroyOnLoad enabled so it only gets killed when the game stops running.

I don’t know what is the task of this second thread, but I assume it executes this task in a loop. In such case, you can create a class with single bool property which will be used to control this loop, and pass an instance of this class to the new thread. If you want to stop the thread, just set this bool to false. Sample:

public class ThreadingTest : MonoBehaviour {

    class ThreadController
    {
        public bool ShouldExecute { get; set; }
    }

    private int _testValue = 0;
    private ThreadController _threadController;

    void Start()
    {
        _threadController = new ThreadController { ShouldExecute = true };
        Thread t = new Thread(RunThread);
        t.Start(_threadController);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.X))
        {
            _threadController.ShouldExecute = false;
        }
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log(_testValue);
        }
    }

    void RunThread(object data)
    {
        var tc = (ThreadController)data;
        while (tc.ShouldExecute)
        {
            Interlocked.Increment(ref _testValue);
            Thread.Sleep(1000);
        }
    }
}

Please note that this is a really trivial example (POC only), not requiring any special constructs (e.g. lock). Even the Interlocked is not required here… In your case, you need to change to false when user exits a game. And to handle it in editor, you probably need EditorApplication.playmodeStateChanged.

Also, I tested this in editor only, but I suggest testing it after build. Especially for mobiles and web player.