1

I'm wanting to make sure that when my application quits that any and all open threads are closed. However when I try to do so I get the error telling me that there is no reference object for what I'm trying to do, even though it's all in the same class.

Can someone please help me out?

Starting / opening threads:

Thread listen_thread;
TcpListener tcp_listener;
Thread clientThread;


// Use this for initialization
void Start () 
{
    IPAddress ip_addy = IPAddress.Parse(ip_address);
    tcp_listener = new TcpListener(ip_addy, port);
    listen_thread = new Thread(new ThreadStart(ListenForClients));
    listen_thread.Start();


    Debug.Log("start thread");

}

Then my attempt at closing them:

void OnApplicationQuit()
{
    try
    {
        clientThread.Abort();
        tcp_listener.Stop();
        listen_thread.Abort();

    }
    catch(Exception e)
    {
        Debug.Log(e.Message);
    }
}

What am I doing wrong? The threads open and do what they are suppose to just fine, but for some reason I can't close them.

Sean
  • 897
  • 4
  • 20
  • 42
  • My testing (with Unity 5.2 on Windows 7 64-bit) indicates that thread.Abort does not work in Unity unless the thread being aborted sleeps at some point. If your ListenForClients method includes a Thread.Sleep(0) in its main loop then the Abort should work. (Though you won't get a ThreadAbortException, which is another bug ...). – yoyo Oct 19 '15 at 19:05

1 Answers1

2

You shouldn't force a thread to Abort, there is a lot of good answers on SO and web elsewhere on this topic, e.g:

Instead you should implement a cancalation pattern, for example via Task or BackgroundWorker classes. In this case you basically say: "stop or break whatever you doing and just exit the method". You can also roll out your own implementation: query a volatile bool or using event handles, but probably stick to the solutions already available. More info in this answer.

Community
  • 1
  • 1
oleksii
  • 35,458
  • 16
  • 93
  • 163