我正在制作程序,通过FTP获取截图并在网络主机上上传该图像。我有问题,当程序上传图片时,那时PC冻结了第二次,我想第二次是图片上传时的时间。用户不应该感觉某些东西正在减慢他的PC。
如何消除那一秒冻结?
注意:这不是某种类型的病毒
/* 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;
}
这是我的上传功能
答案 0 :(得分:1)
更改方法声明:
public async Task upload(string remoteFile, string localFile)
然后将调用更改为Write:
await ftpStream.WriteAsync(byteBuffer, 0, bytesSent);
该方法中的其余I / O可能足够快,不需要切换到async / await方法。但是你也可以考虑改掉它们。
请注意,您还必须更改upload()
的呼叫网站。你需要"冒泡" async / await模式一直到初始UI事件处理程序,可以是async void
而不是async Task
(这样你就可以匹配所需的事件处理程序方法签名)。
答案 1 :(得分:0)
只要您调用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();
它适用于我,并且不需要“冒泡”异步回复给任何人。