I am trying to create several task (async) they will execute the following logic:
Items 1 and 4, especially 4 take because of the speed of the internet link, so they should be async. But I'm having trouble, all my code runs, but synchronously.
private static void Main(string[] args)
{
IEnumerable<UrlsProdutos> registros = db.UrlsTable.Where(w => w.Lido == false).Take(1000);
ExecutaTarefasAsync(registros).Wait();
}
public static async Task ExecutaTarefasAsync(IEnumerable<UrlsProdutos> registros)
{
var urlTasks = registros.Select((registro, index) =>
{
Task downloadTask = default(Task);
//parsing html
var produtoTask = ExtraiDados.ParseHtml(registro.Url);
if (produtoTask.IsCompleted)
{
var produto = produtoTask.Result;
//aqui faço um insert com Dapper
downloadTask = InsertAdo.InsertAdoStpAsync(produto);
}
//marca url como lida, igual ao insert do produto
InsertAdo.MarcaComoLido(registro.UrlProdutoId);
Output(index);
return downloadTask;
});
await Task.WhenAll(urlTasks);
}
public static void Output(int id)
{
Console.WriteLine($"Executando {id.ToString()}");
}
The insert made a fixed just to test
public static async Task InsertAdoStpAsync(Imovel imovel)
{
var stringConnection = db.Database.Connection.ConnectionString;
var con = new SqlConnection(stringConnection);
var sqlQuery = "insert tblProdutos...etc..etc"
con.ExecuteAsync(sqlQuery);
}
I do not know if each function should be async. or if I could select type Download and parse be async ..
My async photo download system works perfectly.
public static async Task DownloadData(IEnumerable<FotosProdutos> urls)
{
var urlTasks = urls.Select((url, index) =>
{
var filename = "";
var wc = new WebClient();
string path = "C:\teste\" + url.FileName;
var downloadTask = wc.DownloadFileTaskAsync(new Uri(url), path);
return downloadTask;
});
await Task.WhenAll(urlTasks);
}
I need help to make and understand how the Execute TasksAsync is actually async equal to the photos that I have not even been able to incorporate into this project.
NOTE: I do not know if I download the photos in the parse or if I put this task.