c# - 将同步方法变为异步(FTP/上传)

标签 c# .net winforms ftp

我需要通过 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/

相关文章:

c# - TextBox - TextChanged 事件 Windows C#

c# - IE 和 Mozilla Firefox 之间的 JavaScript 行为差异?

c# - 在远程网站使用论坛数据库创建 C# 身份验证?

c# - 如何在C#.NET中修改其他Form的RichTextBox

asp.net - 多个 DataContext 类是否合适?

C# WinForms 序列不包含元素

c# - 从另一个类 C# .NET 调用表单类中的函数

c# - 如何在 xamarin.forms 中绑定(bind)标签的 Horizo​​ntalOptions 属性

c# - MVC 5 路由问题 - 多个路由错误地针对同一 View

c# - 如何在 XDocument.Load(string uri) 上设置超时?