【发布时间】:2018-09-26 07:21:57
【问题描述】:
我正在为我的大学学位创建一个远程管理工具。我目前确实遇到了代码中的一个错误,想知道是否有人可以对我的问题有所了解。
我有应用程序、服务器和客户端。服务器运行良好。但是客户端是冻结的应用程序。
在连接到服务器之前,客户端可以正常工作。当连接到服务器时,客户端一直在屏幕上冻结。
我已将错误范围缩小到特定代码段,如果没有运行此代码,应用程序不会冻结。但是,该应用程序也不起作用。
这是该代码的示例:
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;
}
}
if (!isFileDownload) //Not downloading files
{
string text = (!IsLinuxServer) ? Encoding.Unicode.GetString(data) : Encoding.UTF8.GetString(data); //Convert the data to unicode string
string[] commands = GetCommands(text); //Get command of the message
foreach (string cmd in commands) //Loop through the commands
{
HandleCommand(Decrypt(cmd)); //Decrypt and execute the command
}
}
}
catch (Exception ex) //Somethind went wrong
{
MessageBox.Show(ex.Message);
RDesktop.isShutdown = true; //Stop streaming remote desktop
// MessageBox.Show("Connection ended");
}
}
此代码是用户如何接收来自服务器的请求。所以它在一个定时器中每 100 毫秒运行一次。
我想知道计时器是否与它有关。在它处于 While(true) 循环之前,我遇到了同样的问题,这让我认为这是导致 UI 冻结的实际代码。
即使应用程序被冻结,代码仍然可以工作,应用程序上的所有内容都可以正常工作,除了 UI。
这真的令人沮丧,我真的看不出代码有什么问题会导致应用程序冻结。
任何帮助将不胜感激。
提前谢谢你。
【问题讨论】:
-
你需要以
asynchronous的方式运行这段代码。 -
您在 UI 线程上执行的任何操作都会阻止 UI 线程执行其他任何操作。这就是为什么你不应该做任何在 UI 线程上运行很长时间的事情。如果您需要收集数据,请在辅助线程上执行此操作,然后仅编组回 UI 线程以实际更新 UI。阅读有关并行、多线程和异步编程的知识。
-
你写
if (x) { ... } if (!x) { ... }而不是if (x) { ... } else { ... },你觉得奇怪吗?我觉得很奇怪。为什么选择这种方式来编写 if-else? -
更一般地说,在我看来,这段代码正在做四件事:(1) 通过普通套接字下载文件,(2) 通过 ssl 套接字下载文件,(3) 通过普通套接字,(4) 通过 ssl 套接字下载文本。这里似乎缺少一些可以从现有部分轻松构建的抽象,这将使这段代码更简单、更容易理解。 计算机编程是制作有用抽象的艺术。您的代码在这里缺乏抽象。
-
考虑会发生什么是请求需要 > 100 毫秒。
标签: c# winforms user-interface