【发布时间】:2016-01-26 00:28:18
【问题描述】:
我将 LINQ 与 EntityFramewwork 6 一起使用,并且我需要将大部分方法转换为异步任务。
但是,我无法弄清楚为什么在这两个特定场景中我会收到这些设计时编译消息。如果有人可以向我解释我需要做什么才能使任务异步,将不胜感激。
我要转换的第一类同步任务如下:
public List<Category> GetProjectsByCategoryID(Int16 categoryid)
{
try
{
using (YeagerTechEntities DbContext = new YeagerTechEntities())
{
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Database.Connection.Open();
var category = DbContext.Categories.Include("Projects").Where(p => p.CategoryID == categoryid).ToList();
return category;
}
}
catch (Exception ex)
{
throw ex;
}
}
当我尝试将上述方法更改为异步任务时(见下文),我不知道该放置什么异步方法inbetween the "Include("Projects").(p"
public async Task<List<Category>> GetProjectsByCategoryID(Int16 categoryid)
{
try
{
using (YeagerTechEntities DbContext = new YeagerTechEntities())
{
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Database.Connection.Open();
var category = await DbContext.Categories.Include("Projects").(p => p.CategoryID == categoryid);
return category;
}
}
catch (Exception ex)
{
throw ex;
}
}
如何将这种同步方法转换为异步方法?
public List<CustomerEmail> GetCustomerDropDownList()
{
try
{
using (YeagerTechEntities DbContext = new YeagerTechEntities())
{
DbContext.Configuration.ProxyCreationEnabled = false;
DbContext.Database.Connection.Open();
var customers = DbContext.Customers.Select(s =>
new CustomerEmail()
{
CustomerID = s.CustomerID,
Email = s.Email
}).ToList();
return customers;
}
}
catch (Exception ex)
{
throw ex;
}
}
【问题讨论】:
-
你为什么要
catch (Exception ex){ throw ex;}?即使throw ex;之前有记录代码,您也应该永远只调用throw ex;,这样您就破坏了堆栈跟踪,并且从中一无所获。您应该只调用throw;以保留堆栈跟踪,或者调用throw new SomeOtherException("Some descriptive text", ex)以便ex将作为内部异常返回。 -
谢谢,我会做出改变的......
-
Scott,如果我将其保留为“throw ex”,那不会回到调用方法,点击“catch”并处理 ex.Message 异常吗?
-
那么在这个方法中根本不要catch或者使用
throw;而不是throw ex;。ex.StackTrace;被替换为指向throw ex;位置的新堆栈跟踪。如果您只使用throw或者在引发错误的实际位置没有捕获所有堆栈跟踪点。阅读this SO question了解更多信息。 -
知道了...谢谢。我将对代码进行更改....
标签: c# multithreading linq entity-framework