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.