我已經建立了具有被執行以下任務的若干後臺線程一個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