您可以使用System.Threading.Tasks.Task调用StartNew方法与Action delegate。
使用这些工具,你的控制器会是这个样子:
[HttpPost]
public ActionResult DoSomethingLongRunning()
{
if (ModelState.IsValid)
{
Task.Factory.StartNew(() =>
fileCopier.CopyFile(CopyFileParameter1, CopyFileParameter2));
return RedirectToAction("View Indicating Long Running Progress");
}
else
{
// there is something wrong with the Post, handle it
return View("Post fallback view");
}
}
另一种选择是,你可以使用System.Reactive.Concurrency和IScheduler接口TaskPoolScheduler为具体落实执行动作(控制器构造可能注入。
public ActionResult DoSomethingLongRunning()
{
if (ModelState.IsValid)
{
ISchedulerImplementation.Schedule(new Action(() =>
{
fileCopier.CopyFile(CopyFileParameter1, CopyFileParameter2);
}));
return RedirectToAction("View Indicating Long Running Progress");
}
else
{
// there is something wrong with the Post, handle it
return View("Post fallback view");
}
}
作为一个好处,如果你做这种方式,您可以使用TestScheduler当你在单元测试接口的实现。
对于MVC 3,看我的MSDN文章:http://msdn.microsoft.com/en-us/library/ee728598(VS.98).aspx如果你可以使用MVC 4和Developer Express公司11,我编写一个简单得多的新的Async/MVC教程。 – RickAndMSFT 2012-03-28 17:34:53