我希望能够如下运行异步调用:
[Route("doit"),ResponseType(typeof(MyModel))]
public IHttpResponse PostAsyncCall(MyModel model){
//Code removed for simplicity
Task.Factory.StartNew(() => asyncStuff(model.id);
return OK(model);
}
private void asyncStuff(int id) {
MyModel model = db.MyModels.find(id);
//Do things here. Long call to other webservices/processing of data. Time intensive normally.
User user = db.Users.find(model.userId);
//Do more things. Time intensive normally.
}
但是,当异步方法命中
db.
方法时,会发生错误:EntityFramework.dll中发生类型'System.InvalidOperationException'的异常,但未在用户代码中处理
附加信息:由于已处置DbContext,因此无法完成操作。
这里使用的上下文是:
public class MyContext : DbContext, MyContextInterface
{
// You can add custom code to this file. Changes will not be overwritten.
//
// If you want Entity Framework to drop and regenerate your database
// automatically whenever you change your model schema, please use data migrations.
// For more information refer to the documentation:
// http://msdn.microsoft.com/en-us/data/jj591621.aspx
public MyContext() : base("name=MyContext")
{
}
public System.Data.Entity.DbSet<MyAPI.Models.User> Users { get; set; }
public System.Data.Entity.DbSet<MyAPI.Models.Request> Requests { get; set; }
public void MarkAsModified(Object item)
{
Entry(item).State = EntityState.Modified;
}
}
通过以下方式在控制器中将上下文创建为类变量:
private MyContextInterface db = new MyContext();
我可以看到随着方法的结束,db上下文将被丢弃。但是,我需要在异步方法期间保留此上下文,以访问所需的信息。我怎样才能做到这一点?
最佳答案
您启动了任务,但没有等待它,因此有效地,您立即致电OK。
当长时间运行的任务完成时,实际上您的数据库上下文已被处置。
只需添加一个等待,您的问题将得到解决。