Download async with Webclient.Downloadfileasync

Asked

Viewed 1,242 times

3

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

But I think I’m making trouble 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 I wanted to transform into multiple downloads at the same time.

today 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: I tried to do so: dImg.DownloadAsync(); //here normal in the Downloadimage class 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 a manager or an asynchronous module or during certain life cycle events of the page. If the exception occurred during the execution of a page, check that it is marked as <%@Page Async = "true"%>. This exception may also indicate a call attempt for a "asynchronous empty", normally not supported in the elaboration of ASP.NET. The asynchronous method must return a task and the caller has to wait.

1 answer

1


I had 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!");
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.