我需要通过 FTP 将文件上传到我的服务器,但现在已经不是 1995 年了,所以我想我可能想让它异步或在后台上传文件,以免使 UI 变得无响应。
代码来自this页面有一个通过 FTP 同步上传文件方法的完整示例。如何将其转换为异步方法?
同步代码:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="aec4cfc0cbeac1cbeecdc1c0dac1ddc180cdc1c3" rel="noreferrer noopener nofollow">[email protected]</a>");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();
}
}
}
}
我应该把它扔进BackgroundWorker吗?
注意事项:
我不需要知道传输/上传的进度。我需要知道的只是状态(正在上传或已完成)。
最佳答案
Should I just throw it into a BackgroundWorker?
没有。此类操作受 I/O 限制。当线程池线程等待下载响应流/读取文件时,您会浪费线程池线程。
您应该考虑使用 async versions of the methods you've used above以及async
/await
的魔力。这将使您避免浪费线程池线程,而是依赖 I/O 完成来完成任务。
关于c# - 将同步方法变为异步(FTP/上传),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22799532/