I’m trying to figure out how to make a Thread exit upon quitting the application in the unity editor (Clicking play again); The reason I’m using another thread is for my networking, I have a custom stand-alone server that I’m writing and I don’t want it to dead-lock anything in the game while waiting on data to be received. From previous experiences if I’m waiting on data on the main thread, the game doesn’t want to do much of anything besides sit and wait; So I started another thread using System.Threading (C#)
The problem is, when I stop testing the game; The thread is never closed (Everything in that thread keeps processing), how can I fix this? or… what is another solution to run networking parallel to the game, instead of on the same worker thread.
great questions… I’m curious too. I’m guessing you’ve created your own thread manager plugin to handle the tasks?.. would you then perhaps keep track internally of separate threads, and send a “kill all” on exit?
I think we cleared this up in another thread, but for other people’s reference you just need something like this in your MonoBehaviour that’s managing the thread:
public void OnApplicationQuit()
{
if (Application.isEditor)
{
// signal your threads to exit
}
}
Edit: As fholm said in the other thread, it may be better to use OnDestroy, so you also kill the thread any time the MonoBehaviour responsible for it is destroyed during runtime. Otherwise when the application exits, if the MonoBehaviour has already been destroyed or disabled, it won’t receive the OnApplicationQuit notification.
public void OnDestroy()
{
// signal your threads to exit
}