Ronaldo Lemos
Ronaldo Lemos

Reputation: 11

C# async method does not return to caller as expected

I have a series of asynchronous functions that are cascaded, but when it finishes executing the last, it does not return the values ​​to the previous ones.

This is where my first call is run. This is a WebAPI function and always comes to an end.

    [HttpGet]
    [Route("integracao/iniciar")]
    public IHttpActionResult FazerIntegrar()
    {
        try
        {
            Integrar objIntegrar = new Integrar();

            return Ok(objIntegrar.Integra());
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

    }

so my function is in my library is called. Within my function I have a for executing only once. The flow is never resumed by it to continue the loop

public async Task<bool> Integra()
    {
        var files = Directory.GetFiles(@"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\");

        bool retorno = false;

        if (files != null)
        {
            foreach (var item in files)
            {
                retorno = false;

                using (StreamReader sr = new StreamReader(item))
                {
                    if (sr != null)
                    {
                        while (sr.EndOfStream == false)
                        {
                            string line = await sr.ReadLineAsync();

                            string[] grupo = line.Split(new[] { "#*#" }, StringSplitOptions.None);

                            procData objProc = new procData();

                            objProc.proc = grupo[0];

                            objProc.name = JsonConvert.DeserializeObject<List<string>>(grupo[1]);
                            objProc.valor = JsonConvert.DeserializeObject<List<object>>(grupo[2]);
                            objProc.tipo = JsonConvert.DeserializeObject<List<Type>>(grupo[3]);

                            _context = new IntegrarRepository("online_pedidopizza");

                            retorno = await _context.IntegrarAsync(objProc);

                            //retorno = await _context.IntegrarAsync(objProc);
                        }
                    }
                }

                if (retorno == true)
                {
                    await DeleteAsync(item);
                }
            }
        }

        return retorno;
    }

I have a third function just to mediate with the repository

        public async Task<bool> IntegrarAsync(procData objProc)
    {
        return await this.SendIntegrarAsync(objProc);
    }

And finally, communication with the database, all code is executed correctly. Debugging you can get to the end of this fourth function but then the debug stop and does not go back to the beginning

protected async Task<bool> SendIntegrarAsync(procData parametro)
    {
        bool retorno = false;

        using (SqlConnection conn = new SqlConnection(""))
        {
            using (SqlCommand cmd = new SqlCommand(parametro.proc, conn))
            {
                cmd.CommandType = CommandType.StoredProcedure;

                if (parametro != null)
                {
                    for (int i = 0; i < parametro.name.Count; i++)
                    {
                        AdicionaParametro(cmd, parametro.name[i], parametro.valor[i], parametro.tipo[i]);
                    }
                }

                try
                {
                    cmd.CommandTimeout = 300;

                    await conn.OpenAsync().ConfigureAwait(false);

                    var resultado = await cmd.ExecuteScalarAsync().ConfigureAwait(false);

                    if (resultado != null)
                    {
                        retorno = Convert.ToBoolean(resultado);
                    }
                }
                catch (Exception ex)
                {
                    Logs objLog = new Logs()
                    {
                        metodo = MethodBase.GetCurrentMethod().Name,
                        classe = this.GetType().Name,
                        dados = parametro,
                        data = DateTime.Now,
                        mensagem = ex.Message,
                        exception = ex.InnerException == null ? "" : ex.InnerException.ToString()
                    };

                    objLog.Adiciona();

                    string name = DateTime.Now.ToBinary().ToString();

                    using (StreamWriter sw = new StreamWriter(@"C:\inetpub\wwwroot\Atendup\Arquivos\Backup\" + name + ".txt"))
                    {
                        string line = "";

                        line += parametro.proc + "#*#";
                        line += JsonConvert.SerializeObject(parametro.name) + "#*#";
                        line += JsonConvert.SerializeObject(parametro.valor) + "#*#";
                        line += JsonConvert.SerializeObject(parametro.tipo) + "#*#";

                        sw.WriteLine(line);
                    }
                }
            }
        }

        return retorno;
    }

What should I have to do? Thanks

Upvotes: 0

Views: 323

Answers (1)

mcbowes
mcbowes

Reputation: 798

Your Web Api call is not async try changing it to:

[HttpGet]
[Route("integracao/iniciar")]
public async Task<IHttpActionResult> FazerIntegrar()
{
    try
    {
        Integrar objIntegrar = new Integrar();

        return Ok(await objIntegrar.Integra());
    }
    catch (Exception ex)
    {
        return InternalServerError(ex);
    }

}

Upvotes: 2

Related Questions