【发布时间】:2014-04-11 12:03:24
【问题描述】:
我正在开发一款多人游戏,使用 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;
}
}
}
}
}
如您所见,当 bool 运行为 true 时会运行一个 while 循环(是的,我在声明时将其设置为 true。)。
现在,在连接按钮等的 GUI 类中,我有一个对 OnApplicationQuit 的函数调用,如下所示:
void OnApplicationQuit()
{
client.running = false;
client.Disconnect();
Debug.Log(client.running);
Debug.Log("Bye");
}
但是,运行的变化并没有到达线程(我相信线程是在变量的缓存版本上运行的?)。所以我的问题是,当程序关闭时如何使while循环停止? (我试过在OnApplicationQuit()中的线程上调用.Abort()函数,但是也没用。
另外,我知道除非您需要,否则通过网络发送字符串效率不高(所以无需告诉我!)
【问题讨论】:
标签: c# multithreading networking unity3d