Webclientdownloadfiletaskasync file in use, even with Dispose

Asked

Viewed 27 times

1

I am downloading 10 images at the same time async way, However in the 2nd photo usually the error that the image is in use.

The process can not access the file because it is being used by Another process.

I find it strange, because the old code that moved the images after the download has already been removed, IE, I’m not doing anything beyond the download, so should not give this error.

My code is like this:

    public static async Task DownloadImgAsync(IEnumerable<FotosProduto> urls, int id)
    {
//recebe uma lista com 10 urls para download
            var urlTasks = urls.Select((url, index) =>
            {
                using (var wc = new WebClient())
                {
                    var urlTratada = url.Url.Replace(" ", "").Replace("\n", "");
//garantindo que a url está correta
                    var path = Caminhos.FolderImg + url.FileNameFinal;
//aqui só recupero a pasta default das minhas imagens + o nome final da foto
                    var downloadTask = wc.DownloadFileTaskAsync(new Uri(urlTratada), path);
//insere o processo na task de download
                    wc.Dispose(); //redudante pelo using, mas ainda sim pra tentar evitar o erro.
                    return downloadTask;
                }
            });

            await Task.WhenAll(urlTasks);
    }

See that I’ve put him with using and for the sake of conscience I still call dispose, but it always returns that the image is in use. as?

NOTE: This function is called for each product, usually I have a large list of products running ex: 1000mil products and each product 10 images.

Other questions related to the same project:

Download Async + Copy = Copying image 0 bytes

await Task.Whenall how to run multiple processes?

  • 1

    Have you checked if he is trying to download the same image at the same time? If this is the case path your can have the same value in two tasks at the same time, then it would give that error.

  • perfect answer, it may be that my random generator is not so random so, it would justify the failure...I will test

  • At the level of testing (or production, will know) makes the name using a DateTime.Now.Ticks + Random...

1 answer

1


the problem was for some reason my function of generating random name was not so random:

  public string GerarNomeJPG(int _size)
        {
            var random = new Random((int)DateTime.Now.Ticks);
            var builder = new StringBuilder();
            char ch;
            for (int i = 0; i < _size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            builder.Append(".jpg");
            return builder.ToString().ToLower();
        }

Solution thanks to the comment of @Ricardo

Browser other questions tagged

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