C# 线程将不会关闭,不会';似乎达不到变化的变量
我正在开发一款多人游戏,使用C# 线程将不会关闭,不会';似乎达不到变化的变量,c#,multithreading,networking,unity3d,C#,Multithreading,Networking,Unity3d,我正在开发一款多人游戏,使用lidgren库进行联网 我当前在读取从我的服务器发送的邮件的my函数中遇到问题。 函数如下所示: public class Client { /* code omitted */ public void ReadMessage() { //Read Messages while (running) { Debug.Log("InREAD"); //w
lidgren
库进行联网
我当前在读取从我的服务器发送的邮件的my函数中遇到问题。
函数如下所示:
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;
}
}
}
}
}
void OnApplicationQuit()
{
client.running = false;
client.Disconnect();
Debug.Log(client.running);
Debug.Log("Bye");
}
如您所见,当bool running为true时,会运行一个while循环(是的,我在声明时将其设置为true)
现在,在我的GUI类中,用于连接的按钮是etc,我有一个对应用程序退出的函数调用,如下所示:
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;
}
}
}
}
}
void OnApplicationQuit()
{
client.running = false;
client.Disconnect();
Debug.Log(client.running);
Debug.Log("Bye");
}
但是,运行的更改没有到达线程(我相信线程是在缓存的变量版本上运行的?)。所以我的问题是,当程序关闭时,如何使while循环停止?(我尝试在应用程序退出()中的线程上调用.Abort()
函数,但也不起作用
另外,我知道通过网络发送字符串不是很有效,除非您需要(所以无需告诉我!)只是猜测一下(因为我不知道librarylidgeren
):难道您的线程不可能卡在调用wClient.ReadMessage()中吗
仅仅因为您没有收到来自客户端的任何消息?如果wClient.ReadMessage()
是一个阻塞调用,那么产生的行为就是您描述的行为
此外:即使调用Thread.Abort()
也无法工作,因为线程处于睡眠状态(因为它正在等待来自网络连接的消息):只要wClient.ReadMessage()
返回,线程就会被中止。查看MSDN,它会告诉您“如果在托管线程执行非托管代码时对其调用Abort,则在该线程返回托管代码之前不会引发ThreadAbortException”,假设ReadMessage()
在某个时刻将执行系统调用,只是为了等待来自底层套接字的一些数据。您必须调用client.Shutdown()
断开呼叫是否应该中断ReadMessage功能?@ThaMe90:我不知道……正如我所说的,我不知道如何lidgren
,您的问题的答案取决于ReadMessage()的方式
已在lidgren中实现。这并没有提供问题的答案。若要评论或要求作者澄清,请在其帖子下方留下评论。哦,你是对的;我没有充分阅读问题。NetClient.ReadMessage()不会阻止,但会调用Shutdown()应该在退出应用程序时执行(因为它将结束网络线程)。