Turning a Synchronous method async (FTP/Upload)

2019-05-23 07:25发布

问题:

I need to upload files via FTP to my server, but it's not 1995 anymore so I was thinking that I probably want to make it asynchronous or upload the files in the background so as to not make the UI become unresponsive.

The code from this page has a full example of a synchronous method of uploading files via FTP. How can I turn this into an Asynchronous method?

The synchronous code:

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();
            }
        }
    }
}

Should I just throw it into a BackgroundWorker?

things to note:

I don't need to know the progress of the transfer/upload. All I need to know is the status (Uploading or Completed).

回答1:

Should I just throw it into a BackgroundWorker?

No. These sorts of operations are I/O bound. You would be wasting a Thread Pool thread while it waits to download the response stream/read files.

You should look into using the async versions of the methods you've used above and the magic that is async/await. This will save you from wasting a Thread Pool thread and instead will rely on I/O completion to complete the task.