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

时间:2022-01-16 16:14:47

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.

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

    [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

我该怎么办?谢谢

1 个解决方案

#1


2  

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

您的Web 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);
    }

}

#1


2  

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

您的Web 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);
    }

}