应该创建一个对象,发送一个 id,然后在数据库中处理它的代码。问题是我不明白如何先返回答案,然后才使用数据库中的这个对象。
// POST /task
[HttpPost]
public IActionResult Post([FromBody]string value)
{
Task task = new Task { Id = Guid.NewGuid(), Status = "created", Time = DateTime.Now };
db.Tasks.Add(task);
db.SaveChanges();
//await WaitTwoMinutesAndFinish();
System.Threading.Tasks.Task t = new System.Threading.Tasks.Task(() =>
{
using (db)
{
var result = db.Tasks.SingleOrDefault(x => x.Id == task.Id);
if (result != null)
{
result.Status = "running";
result.Time = DateTime.Now;
db.SaveChanges();
}
//else
//return 1;
Thread.Sleep(3000);
// status = finished
result.Status = "finished";
result.Time = DateTime.Now;
db.SaveChanges();
}
});
t.Start();
//UpdateRecord(task);
return Accepted(task.Id);
}
但是当我发送请求时,抛出异常(在 var 结果行上):
Cannot access a disposed object.
A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application.
This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement.
If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
如果您根本不知道为什么需要这样做,那么您可以编写此方法
并像这样从您的代码中调用它
这不会创建新线程并且应该可以工作。但是我根本不清楚为什么要这样做。
为了能够创建数据上下文,您可以引入服务提供者,这是默认容器。如何做到这一点的一个例子: