gpt4 book ai didi

c# - 上传图片时 PC 卡住一秒

转载 作者:太空宇宙 更新时间:2023-11-03 13:15:21 24 4
gpt4 key购买 nike

我正在制作截取屏幕截图并通过 FTP 将该图像上传到 Web 主机的程序。我有问题,当程序上传图片时,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;
}

这是我的上传功能

最佳答案

更改方法声明:

public async Task upload(string remoteFile, string localFile)

然后将调用更改为 Write:

await ftpStream.WriteAsync(byteBuffer, 0, bytesSent);

该方法中的其余 I/O 可能足够快,不需要切换到异步/等待方法。但您也可以考虑将它们切换过来。

请注意,您还必须更改 upload() 的调用站点。您需要将异步/等待模式“冒泡”到初始 UI 事件处理程序,它可以是 async void 而不是 async Task(所以您可以匹配所需的事件处理程序方法签名)。

关于c# - 上传图片时 PC 卡住一秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26564002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com