线程不会关闭,似乎没有达到变化的变量

时间:2014-04-11 12:03:25

标签: c# multithreading networking unity3d

我正在开发一款多人游戏,使用lidgren库进行联网。

我目前遇到的问题是我的函数读取从我的服务器发送的消息。 该函数如下所示:

public class Client
{
    /* code omitted */

    public void ReadMessage()
    {   
        //Read Messages
        while (running)
        {
        Debug.Log("InREAD");
           //wClient is a NetClient (lidgren library)
        NetIncomingMessage msg;
        while ((msg = wClient.ReadMessage()) != null)
        {

            switch (msg.MessageType)
            {
                case NetIncomingMessageType.Data:

                    if (msg.ReadString().Contains("Position"))
                    {
                        Debug.Log("Hej");
                        /*string temp = msg.ReadString();
                    string[] Parts = temp.Split(" ");

                    int x = int.Parse(Parts [1]);
                    int y = int.Parse(Parts [2]);
                    int z = int.Parse(Parts [3]);*/


                        //set player position to xyz values below
                    } else if (msg.ReadString().Contains("Instantiate"))
                    {
                        Debug.Log("Instantiate");
                        /* string temp = msg.ReadString();
                        string[] Parts = temp.Split(" ");*/

                    }
                    break;

            }
        }
        }
    }
}

正如你所看到的,有一个while循环在bool运行为true时运行(是的,我在声明时将其设置为true。)。

现在,在我的GUI类中,连接按钮等,我有OnApplicationQuit的函数调用,如下所示:

void OnApplicationQuit()
{
    client.running = false;
    client.Disconnect();
    Debug.Log(client.running);
    Debug.Log("Bye");
}

但是,运行的更改没有到达线程(我相信线程正在变量的缓存版本上运行?)。所以我的问题是,当程序关闭时,如何使while循环停止? (我试过调用.Abort()中线程上的OnApplicationQuit()函数,但它也不起作用。

另外,我知道通过网络发送字符串效率不高,除非你需要(所以不需要告诉我这个!)

2 个答案:

答案 0 :(得分:0)

猜测(因为我不知道库lidgren):你是不是因为你没有从客户端收到任何消息而将线程卡在wClient.ReadMessage()中?如果wClient.ReadMessage()是阻止调用,则结果行为将是您描述的行为。

此外:即使调用Thread.Abort()也无效,因为线程处于休眠状态(因为它正在等待来自网络连接的内容):线程将在您{{1}时中止返回。查看MSDN here它告诉“如果在执行非托管代码时在托管线程上调用Abort,则在线程返回托管代码之前不会抛出ThreadAbortException”这正是您的假设wClient.ReadMessage()在某个时刻执行系统调用只是为了等待来自底层套接字的某些数据。

答案 1 :(得分:0)

您必须致电client.Shutdown()