Async method returning a Liststring how to use?

2

I have a method called consulta_usuario_email , which is responsible for searching the registered users table, the emails of the users of a certain department:

 public async Task<List<string>> consulta_usuario_email(string departamento)
    {
        consql.bd_string();
        SqlConnection sqlconn = new SqlConnection(consql.sqlconn);

        List<string> email = new List<string>();

        try
        {
            consql._sql = @"select a.Email
                            from AspNetUsers as a
                            left join Empresa_departamento as c
                            on a.Departamento = c.id
                            where c.departamento = @departamento";

            SqlCommand cmd = new SqlCommand(consql._sql, sqlconn);

            cmd.Parameters.Add("@departamento", SqlDbType.VarChar).Value = departamento;

            await sqlconn.OpenAsync();

            using (SqlDataReader leitor = await cmd.ExecuteReaderAsync())
            {
                while (leitor.Read())
                {
                    email.Add(leitor["Email"].ToString());
                }
            } 
        }
        catch (Exception error)
        {
            MessageBox.Show("Erro" + "\n" + error);
        }
        finally
        {
            sqlconn.Close();
        }

        return email;
    } // consulta o email do usuario conforme seu departamento

I want to execute this method Async , and then when it is finished, I want to execute another method that receives as parameters the List generated by method consulta_usuario_email

 Task<List<string>> Mail_PCP = Email_User.consulta_usuario_email("PCP");

          if (Mail_PCP.IsCompleted == true)
          {
              Mail_Urgente.Send(Mail_Compras, Mail_PCP, "Teste", "Teste");
          }

However, how do I pass List to method Send of class Mail_Urgente ?

Update - ref. the @LINQ developer response:

  

"Just use await, like this:"

List<string> Mail_PCP = await Email_User.consulta_usuario_email("PCP");
Mail_Urgente.Send(Mail_Compras, Mail_PCP, "Teste", "Teste");

When trying to do as above the error is generated:

    
asked by anonymous 05.07.2017 / 17:22

1 answer

2

Just use await , like this.

List<string> Mail_PCP = await Email_User.consulta_usuario_email("PCP");
Mail_Urgente.Send(Mail_Compras, Mail_PCP, "Teste", "Teste");

Remember that the method that calls consulta_usuario_email needs to be marked with async .

You can test this with this code:

using System;
using System.Threading.Tasks;
using System.Collections.Generic;

public class Program
{
    public async static void Main()
    {
        var lista = await TaskTeste();      
        lista.ForEach(Console.WriteLine);       
    }

    public async static Task<List<string>> TaskTeste()
    {
        return await Task.Run(() => (new List<string> { "LINQ", "teste" }));
    }
}

See working in .NET Fiddle.

    
05.07.2017 / 17:34