我為我的大學(xué)學(xué)位創(chuàng)建了一個(gè)遠(yuǎn)程管理工具。我目前確實(shí)停留在我的代碼中的一個(gè)錯(cuò)誤,并且想知道是否有人可以闡明我的問(wèn)題。我有應(yīng)用程序,服務(wù)器和客戶端。服務(wù)器運(yùn)行正常。但是,客戶端是凍結(jié)的應(yīng)用程序。在連接到服務(wù)器之前,客戶端可以正常工作。連接到服務(wù)器后,客戶端將不斷凍結(jié)在屏幕上。我已將錯(cuò)誤縮小到特定的代碼段,而沒(méi)有運(yùn)行該代碼的應(yīng)用程序就不會(huì)凍結(jié)。但是,該應(yīng)用程序也不起作用。這是該代碼的示例:private static void ReceiveResponse() { var buffer = new byte[2048]; //The receive buffer try { int received = 0; if (!IsLinuxServer) received = _clientSocket.Receive(buffer, SocketFlags.None); //Receive data from the server else received = _sslClient.Read(buffer, 0, 2048); if (received == 0) return; //If failed to received data return var data = new byte[received]; //Create a new buffer with the exact data size Array.Copy(buffer, data, received); //Copy from the receive to the exact size buffer if (isFileDownload) //File download is in progress { Buffer.BlockCopy(data, 0, recvFile, writeSize, data.Length); //Copy the file data to memory writeSize += data.Length; //Increment the received file size if (writeSize == fup_size) //prev. recvFile.Length == fup_size { using (FileStream fs = File.Create(fup_location)) { Byte[] info = recvFile; // Add some information to the file. fs.Write(info, 0, info.Length); } Array.Clear(recvFile, 0, recvFile.Length); SendCommand("frecv"); writeSize = 0; isFileDownload = false; return; } }此代碼是用戶從服務(wù)器接收請(qǐng)求的方式。因此,它是每100毫秒運(yùn)行一次的計(jì)時(shí)器。我想知道計(jì)時(shí)器是否與此有關(guān)。在進(jìn)入While(true)循環(huán)之前,我遇到了相同的問(wèn)題,這使我認(rèn)為這是導(dǎo)致UI凍結(jié)的實(shí)際代碼。即使應(yīng)用程序被凍結(jié),該代碼仍然可以正常工作,除了UI之外,該應(yīng)用程序中的所有內(nèi)容都可以正常工作。這確實(shí)令人沮喪,并且我看不到任何導(dǎo)致應(yīng)用程序凍結(jié)的代碼有任何錯(cuò)誤。
3 回答

慕工程0101907
TA貢獻(xiàn)1887條經(jīng)驗(yàn) 獲得超5個(gè)贊
因此為此解決了一些問(wèn)題,沒(méi)有使用異步,但是我最終為此任務(wù)創(chuàng)建了一個(gè)不同的線程。
新線程讓我使用了while(true)循環(huán)來(lái)永遠(yuǎn)循環(huán)接收響應(yīng)。
private void btnConnect_Click(object sender, EventArgs e)
{
ConnectToServer();
Thread timerThread = new Thread(StartTimer);
timerThread.Start();
//StartTimer();
//timerResponse.Enabled = true;
}
private static void StartTimer()
{
while (true)
{
ReceiveResponse();
}
}
這足以滿足我的需要。
- 3 回答
- 0 關(guān)注
- 150 瀏覽
添加回答
舉報(bào)
0/150
提交
取消