使用 C# 在 Unity 中关闭线程 [英] Closing threads in Unity with C#

查看:38
本文介绍了使用 C# 在 Unity 中关闭线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想确保当我的应用程序退出时,所有打开的线程都已关闭.但是,当我尝试这样做时,我收到错误消息,告诉我没有我正在尝试执行的操作的引用对象,即使它们都在同一个类中.

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.

有人可以帮我吗?

开始/打开线程:

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");

}

然后我试图关闭它们:

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.

推荐答案

你不应该强迫一个线程Abort,在这个主题的其他地方,SO 和网络上有很多很好的答案,例如:

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.

相反,您应该实现一个cancalation 模式,例如通过TaskBackgroundWorker 类.在这种情况下,您基本上会说:停止或中断您正在做的任何事情,然后退出该方法".您还可以推出自己的实现:查询 volatile bool 或使用事件句柄,但可能坚持使用现有的解决方案.此答案中的更多信息.

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.

这篇关于使用 C# 在 Unity 中关闭线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆