简体   繁体   English

异步FTP上传文件列表

[英]Async FTP Upload List of Files

I'm trying to loop through a list of images and ftp them to a server. 我正在尝试遍历图像列表,并将它们通过ftp下载到服务器。 It's partially working except for it is still blocking my UI thread. 它仍然在阻止我的UI线程,但部分起作用。 Even though my ftp function is async, I'm guessing because my calling method is not, I'm not getting the results I'm looking for. 即使我的ftp函数是异步的,我也在猜测,因为我的调用方法不是,我没有得到想要的结果。 Here's what I got. 这就是我得到的。 What am I doing wrong? 我究竟做错了什么?

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

    }

马克UploadPicturesasyncawaitUploadPhoto

So I called my UploadPictures function using Task run and that worked. 因此,我使用Task run调用了我的UploadPictures函数,该函数起作用了。 Not sure if thats the most correct way to do it. 不确定这是否是最正确的方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM