转动同步方法异步(FTP /上传)

我需要通过FTP上传文件到我的服务器,但它不再是1995年,所以我想我可能想让它异步或在后台上传文件,以免UI变得无法响应。

此页面中的代码提供了通过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","janeDoe@contoso.com"); // 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吗?

注意事项:

我不需要知道转移/上传的进度。 我需要知道的是状态(上传或完成)。

我应该把它扔进BackgroundWorker吗?

不。这些操作是I / O绑定的。 在等待下载响应流/读取文件时,您将浪费线程池线程。

您应该考虑使用上面使用的方法的异步版本以及async / await的魔力。 这将使您免于浪费线程池线程,而是依靠I / O完成来完成任务。