C#异步方法不会按预期返回调用方

时间:2017-09-05 02:01:32

标签: c# sql-server database asynchronous

我有一系列级联的异步函数,但是当它完成执行最后一个函数时,它不会将值返回给前面的函数。

这是我第一次打电话的地方。这是一个WebAPI功能,并且总是结束。

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

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

    }

所以我的函数在我的库中被调用。在我的函数中,我只执行一次。它永远不会恢复流程以继续循环

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;
    }

我有第三个功能只是为了与存储库进行协调

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

最后,与数据库通信,所有代码都正确执行。调试你可以到第四个函数的末尾但是然后调试停止并且不会回到开头

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;
    }

我该怎么办?感谢

1 个答案:

答案 0 :(得分:2)

您的网络Api呼叫不是异步尝试将其更改为:

[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);
    }

}