上传图像时,电脑会冻结一秒钟
本文关键字:冻结 一秒钟 电脑 图像 | 更新日期: 2023-09-27 18:27:58
我正在制作一个程序,该程序可以截屏并通过FTP将图像上传到web主机上。我有一个问题,当程序上传图像时,电脑会冻结第二秒,我想第二秒就是上传图像的时间。用户一定不要有什么东西正在减缓他的电脑
如何消除一秒钟的冻结?
注意:这不是某种类型的病毒
/* Upload File */
public void upload(string remoteFile, string localFile)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
/* Establish Return Communication with the FTP Server */
ftpStream = ftpRequest.GetRequestStream();
/* Open a File Stream to Read the File for Upload */
FileStream localFileStream = new FileStream(localFile, FileMode.Open);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
/* Upload the File by Sending the Buffered Data Until the Transfer is Complete */
try
{
while (bytesSent != 0)
{
ftpStream.Write(byteBuffer, 0, bytesSent);
bytesSent = localFileStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpRequest = null;
}
catch (Exception ex) { MessageBox.Show(ex.ToString()); }
return;
}
这是我的上传功能
更改方法声明:
public async Task upload(string remoteFile, string localFile)
然后将调用更改为Write:
await ftpStream.WriteAsync(byteBuffer, 0, bytesSent);
该方法中的其余I/O可能足够快,不需要切换到异步/等待方法。但你也可以考虑把它们换掉。
请注意,您还必须更改upload()
的呼叫站点。您需要将async/await模式一直"冒泡"到初始UI事件处理程序,它可以是async void
而不是async Task
(这样您就可以匹配所需的事件处理程序方法签名)。
无论在哪里调用upload()
方法,都可以使用Task
异步运行:
var task = new Task(() =>
{
upload(remotePath, localPath);
});
task.Start();
如果您需要在任务运行时向UI线程报告某些内容。。。。例如,只需使用Dispatcher
:
var task = new Task(() =>
{
upload(remotePath, localPath);
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new Action(() =>
{
DoSomethingToUI();
}));
});
task.Start();
它对我来说效果很好,没有必要"冒泡"异步返回给任何人。