(Problem solved) I have an MVC application, in my Action:
First case: Task never started.
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");
}
Second case: Task run normally
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");
}
My question is: When Task.Factory.StartNew and i put a method into it, the parameter of that method (object) must be declare outside??? Because when i write shortly like the first case, i put the "new" keyword in the parameter and the task never run. Reason: In action, i wanna return view as soon as possible, any other stuff not related to that view will be excute in a task and client no need to wait for completed.
I'm very sorry about my bad english :)
Updated 1: Thanks Panagiotis Kanavos, I used QueueBackgroundWorkItem but the problem still the same, if i declare the object outside, this method run normally. But when i use new keyword inside the parameter, this method never run. No exception, no errors. Can anyone explain to me how this possible :(
Updated 2: I try two case:
First:
HostingEnvironment.QueueBackgroundWorkItem(delegate {
var handler = m_bussinessHandler;
handler.InsertNewsHistoryAsync(new NewsHistoryDto {
UserId = UserModel.Current.UserId,
Time = DateTime.Now,
Id = newsId
});
});-> still doens't works
Second:
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
So where is the problem here??? That's not about m_bussinessHandler because i copied.
Updated 3: I found the reason.
The reason is UserModel.Current, this is an object in HttpContext.Current.Session["UserModel"]
, in this case when i call async method, when this method actually excute, it can access to HttpContext.Current which is null. So i can solve this problem by declare object outside to store data and pass it into method or I capture UserModel.Current and pass it into this method to use UserModel.Current.UserId.
My problem actually solved, thanks everyone for helping me, especially Panagiotis Kanavos.