Closing threads in Unity with C#

梦想与她 提交于 2021-02-08 08:30:31

问题


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.


回答1:


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:

  • Put the thread in its own process. When you want it to stop, kill the process.
  • How To Stop a Thread in .NET (and Why Thread.Abort is Evil)
  • You don't need to cancel the thread.
  • msdn on THread.Abort(). See remarks section.

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.



来源:https://stackoverflow.com/questions/19048191/closing-threads-in-unity-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!