我已经建立了具有被执行以下任务的若干后台线程一个C#WPF应用程序:C#WPF应用程序冻结随着时间的推移
- 多个线程,每个包含一个TCP服务器在while循环每运行他们只是在等待一个消息从一个特定端口
- 一个线程不断地监视一个USB端口的I/O设备
- 一个线程是由微软Kinect设备
- 某些定时调度线程做一些采集数据基于“标志”更新(或静态全局变量)从其他线程引发。
的例子:
Thread thread = new Thread(new ThreadStart(Server));
private static void Server()
{
try
{
IPAddress ipAd = IPAddress.Parse("192.168.1.119");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8003);
/* Start Listeneting at the specified port */
myList.Start();
System.Diagnostics.Debug.Write("The server is running at port 8003...");
System.Diagnostics.Debug.Write("The local End point is :" +
myList.LocalEndpoint);
System.Diagnostics.Debug.Write("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
System.Diagnostics.Debug.Write("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
k = s.Receive(b);
Console.WriteLine("Recieved...");
string temp = "";
for (int i = 0; i < k; i++)
{
System.Diagnostics.Debug.Write(Convert.ToChar(b[i]));
temp += Convert.ToChar(b[i]);
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
System.Diagnostics.Debug.Write("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
if (k > 0)
{
cont = true;
k = 0;
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
所以,我所遇到的问题是,偶尔应用只是冻结了,我不能在所有访问它。主UI线程也冻结了,我甚至不能在Windows中从任务管理器中终止程序。通常情况下,应用程序运行的很好,但长时间使用应用程序后会出现问题(例如4〜5小时)。
我使用的计算机不是只有2G RAM和AMD的高端PC双核CPU。
我对这个问题的猜测可以如下:
- 内存不足(或内存泄漏的地方,但窗口工作正常,只有程序冻结)
- 网络拥塞(即僵局地方,但这似乎并不可能用简单的发送和接收应用程序)
- 无法与USB设备(包括Kinect的)
但是建立的连接,我仍然没有确定如何找出问题。我可能对实现还很陌生,所以我很乐意听到C#WPF,网络和多线程应用程序中的一些专家的意见来帮助我。谢谢。
如果你能够使用.net 4或4.5,我会建议寻找任务并行:http://msdn.microsoft.com/en-us/library/dd537609 .aspx它为长时间运行线程提供了一个选项 – 2013-03-22 00:28:40
while循环?什么while循环?同样,为什么很多ser vers在不同的端口?服务器通常不是这样设计的 - 通常,一个端口上只有一个监听线程,而每个连接只有一个客户端<>服务器线程。 – 2013-03-22 00:29:39
如果您的应用在4-5小时后即将死亡,请尝试使用netstat检查TIME_WAIT中插入了多少个套接字。 – 2013-03-22 00:33:13