c# - 如何执行异步等待函数导入/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;
}
解决方案
我会这样做:
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();
推荐阅读
- php - 使用 nginx 服务器将 URL 重写为 index.php
- html - Django 静态文件引用
- php - AWS Lambda 通过 AWS-PHP-SDK 发送短信不起作用
- ios - 调用可以抛出,但它没有用“try”标记,并且错误未处理/条件绑定的初始化程序必须具有可选类型,而不是“JSON”
- swift - 如何使用 SwiftUI 将数字格式化为带有千分位分隔符的 Text() 字符串值?
- python - 初始化从基类型派生的类
- javascript - Ajax 调用控制器后的 MVC 刷新页面
- html - RVEST 用于 HTML 文件中的日期
- r - R在同一张图表上绘制两个时间序列
- android-studio - 在 Android Studio 中永久显示“文件结构”窗口作为导航工具