c# – Fazer download async com WebClient.DownloadFileAsync

Question:

Today I have a class that downloads photos, but as there are many photos above 5mil I think I could take advantage of the async method. Process several tasks at the same time.

But I think I'm messing with Task<> and Async

 foreach (var item in Produto)
            {
                foreach (var foto in item.Fotos)
                {
                    var NovoNome = txt_IDC.Text + "_" + DownloadImagem.GerarNomeJPG(10);
                        var dImg = new DownloadImagem
                        {
                            NewNomeFile = NovoNome,
                            PathSave = pathFormulario,
                            UrlFoto = foto.UrlFoto
                        };

                        dImg.Download();
                        foto.NomeFoto = NovoNome;
                        }
                }
            }

and my dImg.Download(); calls the method that wanted to make multiple downloads at the same time.

today it is like this:

    public class DownloadImagem
    {
        public string UrlFoto { get; set; }
        public string PathSave { get; set; }
        public string NewNomeFile { get; set; }

    public void Download()
            {
                        using (WebClient cliente = new WebClient())
                        {

                            var pathfinal = PathSave + NewNomeFile;
                            var uri = new Uri(UrlFoto);
                            cliente.DownloadFileAsync(uri, pathfinal); //só isso já serve?
                          //  cliente.DownloadFile(UrlFoto, pathfinal); //assim é como estava
                        }
            }
}

I found a question with something I'd like, but I couldn't understand the logic https://codereview.stackexchange.com/questions/18519/real-world-async-and-await-code-example

EDIT: Tried to do like this: dImg.DownloadAsync(); //here normal in the DownloadImage class that I changed to

public async void DownloadAsync()
        {
            await Task.Run(() => Download());
        }

 public void Download()
        {
                    using (WebClient cliente = new WebClient())
                    {

                        var pathfinal = PathSave + NewNomeFile;
                        var uri = new Uri(UrlFoto);

                        cliente.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
                        cliente.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
                        cliente.DownloadFileAsync(uri, pathfinal);
                    }
        }


        private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
        }

        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
        }

but i get

You cannot start an asynchronous operation at this time. You can initiate an asynchronous operation only within an asynchronous manager or module, or during certain events of the page's lifecycle. If the exception occurred while running a page, make sure it is marked as <% @ Page Async = "true"%>. This exception can also indicate an attempt to call to an "empty asynchronous" method, not normally supported in the elaboration of ASP.NET requests. The asynchronous method must return a task and the caller has to wait.

Answer:

I needed to do something similar recently, follow my code below:

class Program
{
    static void Main(string[] args)
    {
        ToDo();
        Console.ReadLine();
    }

    static async void ToDo()
    {
        await Task.Run(() => Download());
    }

    public static void Download()
    {
        WebClient client = new WebClient();
        Uri ur = new Uri("http://www.culturamix.com/wp-content/gallery/homer-1/homer-simpson.jpg");
        //   client.Credentials = new NetworkCredential("username", "password");
        client.DownloadProgressChanged += WebClientDownloadProgressChanged;
        client.DownloadDataCompleted += WebClientDownloadCompleted;
        client.DownloadFileAsync(ur, @"C:\Users\tadriano\Pictures\homer-simpson.jpg");
        Console.ReadLine();
    }


    static void WebClientDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        Console.WriteLine("Download status: {0}%.", e.ProgressPercentage);
    }

    static void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
    {
        Console.WriteLine("Download finished!");
    }
}
Scroll to Top
AllEscort