2014-04-02 2 views
2

FTP를 통해 파일을 내 서버에 업로드해야하지만 더 이상 1995이 아니므로 비동기로 만들거나 백그라운드에서 파일을 업로드하려고합니다. UI를 응답하지 않게 만들지 마십시오.동기식 메서드 비동기 (FTP/업로드) 전환

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","[email protected]"); 

      // 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에로 던져해야 하는가?

가지주의해야 할 : 나는 전송/업로드의 진행 상황을 알 필요가 없습니다

. 내가 알아야 할 것은 상태 (업로드 또는 완료)뿐입니다.

답변

2

그냥 BackgroundWorker에 넣을까요?

아니요. 이러한 종류의 작업은 I/O 경계입니다. 응답 스트림을 다운로드하거나 파일을 읽으려고 기다리는 동안 스레드 풀 스레드가 낭비됩니다.

async versions of the methods you've used above을 사용하고 async/await 인 마법을 조사해야합니다. 이렇게하면 스레드 풀 스레드를 낭비하지 않고 대신 I/O 완료를 통해 작업을 완료 할 수 있습니다.

+0

감사합니다. 도와 주셔서 정말 고맙습니다. 그래도 재밌 네요. 나는 정말로 검색하는 것을 빨아 먹는 것처럼 보인다. 나는 "비동기 FTP"와 "비동기 FTP"를 검색하는데 30 분을 보냈다. 그 중 대부분은 칠캇 (Chilkat)과 같은 상용 라이브러리였다. – uSeRnAmEhAhAhAhAhA