(问题已解决)我有一个 MVC 应用程序,在我的操作中:
第一种情况:任务从未开始。
public ActionResult Insert(NewsManagementModel model) {
//Do some stuff
//Insert history
//new object NewsHistoryDto as the parameter
Task.Factory.StartNew(() => InsertNewsHistory(new NewsHistoryDto {
UserId = 1234,
Time = DateTime.Now,
Id = 1234
}));
return RedirectToAction("Index", "NewsManagement");
}
第二种情况:任务正常运行
public ActionResult Insert(NewsManagementModel model) {
//Do some stuff
//Insert history
//object NewsHistoryDto was declared outside
var history = new NewsHistoryDto {
UserId = 1234,
Time = DateTime.Now,
Id = 1234
};
Task.Factory.StartNew(() => InsertNewsHistory(history));
return RedirectToAction("Index", "NewsManagement");
}
我的问题是:当我在Task.Factory.StartNew中放入一个方法时,该方法(对象)的参数必须在外面声明???因为当我像第一种情况一样写的时候,我把“new”关键字放在参数中,任务永远不会运行。原因:在行动中,我想尽快返回视图,与该视图无关的任何其他内容将在任务中执行,客户端无需等待完成。
我很抱歉我的英语不好:)
更新 1:感谢Panagiotis Kanavos,我使用了 QueueBackgroundWorkItem但问题仍然存在,如果我在外面声明对象,此方法运行正常。但是当我在参数中使用 new 关键字时,这个方法永远不会运行。没有例外,没有错误。谁能向我解释这怎么可能:(
更新 2:我尝试两种情况:
第一的:
HostingEnvironment.QueueBackgroundWorkItem(delegate {
var handler = m_bussinessHandler;
handler.InsertNewsHistoryAsync(new NewsHistoryDto {
UserId = UserModel.Current.UserId,
Time = DateTime.Now,
Id = newsId
});
});-> still doens't works
第二:
var history = new NewsHistoryDto {
UserId = UserModel.Current.UserId,
Time = DateTime.Now,
Id = newsId
};
HostingEnvironment.QueueBackgroundWorkItem(delegate {
var handler = m_bussinessHandler;
handler.InsertNewsHistoryAsync(history);
});-> works normally
那么问题出在哪里???这与 m_bussinessHandler 无关,因为我复制了。
更新3:我找到了原因。原因是UserModel.Current,这是一个对象HttpContext.Current.Session["UserModel"]
,在这种情况下,当我调用异步方法时,当该方法实际执行时,它可以访问为null的HttpContext.Current。所以我可以通过在外部声明对象来存储数据并将其传递给方法来解决这个问题,或者我捕获 UserModel.Current 并将其传递给这个方法以使用 UserModel.Current.UserId。
我的问题实际上解决了,感谢大家帮助我,尤其是Panagiotis Kanavos。