2014-09-10 98 views
1

我試圖通過圖像列表循環並將它們ftp到服務器。除了它仍然阻塞我的UI線程外,它部分工作。即使我的ftp函數是異步的,我猜測是因爲我的調用方法不是,我沒有得到我期待的結果。這是我得到的。我究竟做錯了什麼?異步FTP上傳文件列表

public void UploadPictures() 
    { 
     //loop through each picture and upload 
     for (int i = 0; i < this.items.Count; i++) { 

      byte[] bytes; 
      if (System.IO.Path.GetExtension (this.items [i].FileName.ToUpper()) == ".JPG") { 
       using (var imageData = this.items[i].Image.AsJPEG()) 
       { 
        bytes = new byte[imageData.Length]; 
        Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length)); 
       } 
       var test=UploadPhoto(bytes, this.items[i].FileName); 

      } 

      if (System.IO.Path.GetExtension (this.items [i].FileName.ToUpper()) == ".PNG") { 
       using (var imageData = this.items[i].Image.AsPNG()) 
       { 
        bytes = new byte[imageData.Length]; 
        Marshal.Copy(imageData.Bytes, bytes, 0, Convert.ToInt32(imageData.Length)); 
       } 
       var test=UploadPhoto(bytes, this.items[i].FileName); 

      } 


     } 



    } 



    public static async Task<string> UploadPhoto(byte[] photoBytes, string filename) 
    { 
     FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://XXXXXXXX/" + filename); 
     request.Method = WebRequestMethods.Ftp.UploadFile; 
     request.Credentials = new NetworkCredential ("user", "pass"); 
     request.UseBinary = true; 

     request.ContentLength = photoBytes.Length; 
     using (Stream s = request.GetRequestStream()) 
     { 
      s.Write(photoBytes, 0,photoBytes.Length); 
     } 
     WebResponse ftpResp = await (Task<WebResponse>)request.GetResponseAsync(); 

     return ftpResp.ToString(); 

    } 

回答

2

馬克UploadPicturesasyncawaitUploadPhoto

+0

我曾嘗試過,無法讓它正常工作。我不記得具體是什麼問題。儘管如此,我使用任務運行,並工作(見我的文章)。謝謝! – darrellbooker 2014-09-11 14:09:40

0

所以我打電話給我的UploadPictures函數使用任務運行和工作。不知道這是否是最正確的方法。

Task.Run(() => 
        { 
         UploadPictures(); 
      });