首页 > 解决方案 > 如何执行异步等待函数导入/SP EF6

问题描述

我有一个函数导入一个存储过程,但我想让它异步。我怎么能那样做?

有任何想法吗?

public static async Task<List<ObtenerLayoutPor_Result>> GenerarArchivoPorBanco()
{
    List<ObtenerLayoutPor_Result> result = new List<ObtenerLayoutPorBanco_Result>();

    try
    {
        using (CobranzaEntities db = new CobranzaEntities())
        {
            return Task.Run(() => db.ObtenerLayoutPor(96)).GetAwaiter(); //one try

            result = await db.ObtenerLayoutPor(96); //second try
        }
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }

    return result;
}

标签: c#sql-serverentity-framework

解决方案


我会这样做:

public static Task<List<ObtenerLayoutPor_Result>> GenerarArchivoPorBanco()
{
  return Task.Run(()=>{ // no await here and function as a whole is not async

        using (CobranzaEntities db = new CobranzaEntities())
        {
            return db.ObtenerLayoutPor(96).ToList(); // depending on your implementation, ToList may be requiered to make the actual trip to database
        }
       });
}

或者,正如评论中所建议的,如果您的存储过程返回 IQueryable,您可以简单地使用以下代码:

public static Task<List<ObtenerLayoutPor_Result>> GenerarArchivoPorBanco()
{
        using (CobranzaEntities db = new CobranzaEntities())
        {
            return db.ObtenerLayoutPor(96).ToListAsync();
        }
}

总而言之,使函数异步的最简单方法是将其包装在 Task.Run 中。然后你可以在你的代码中使用它:

var results = await GenerarArchivoPorBanco();

推荐阅读