Socket continues to operate even after stopping the run

I'm experimenting with using C# sockets directly. They work fine, except for one little problem: they don't break the connection, and in fact continue to work and execute code, even after I've stopped the run in the Unity IDE.

I suspect this is because when you use asynchronous sockets in C#, it automatically creates another thread on which to receive the data. I understand that you need to be careful with these in Unity, catch all exceptions, and don't call into the Unity framework from such a thread. That's all doable, but this part of the app continuing to run even after I've clicked the Stop button is really harshing my buzz.

Anybody know a way to (1) get the Unity IDE to stop all threads (and/or sockets) when you stop the run, short of quitting the whole IDE? Or, (2) get some sort of callback in code when the user stops the run, so I can close the socket myself?

I don’t know if this is the perfect answer, but here is a couple of things I use to do, when working with threads.

  • Add a bool to my threads loop.
    • When I abort my thread, I set the bool to false and check if its aborted properly.

For the socket. Remember to close the stream: client.GetStream().Close();
Else try and call client.Client.Close();