MVC 3任务等待

d1m*_*tar 2 c# asp.net task asp.net-mvc-3

我正在开发一个mvc3项目,该项目正在使用正在进行异步调用的外部sdk.我尝试了以下代码,但它不等待我的任务完成.

public ActionResult Index()
    {
        var price = 0m;
        var t = Task.Factory.StartNew(() =>
                                          {
                                              // calculate price for example                                         });
                                          });
        t.Wait();
        ViewBag.price = price;
        return View();
    }
Run Code Online (Sandbox Code Playgroud)

当我调试时,第一个断点是ViewBag中的价格设置,然后它进入任务.我究竟做错了什么?

Dar*_*rov 5

t.Wait()调用将阻止当前操作的执行,直到任务完成.在您的示例中,任务由您编写的匿名函数表示.当然,如果您在放置注释(// calculate price for example)的位置放置了一些异步代码,那么使用任务和等待就没那么重要了.

所以我想这一切都取决于你在那里执行的具体任务.请记住,阻止ASP.NET MVC应用程序中的主线程是一种非常糟糕的做法.我建议你看一下,asynchronous controllers以优化ASP.NET MVC应用程序中的异步任务的执行,并充分利用I/O完成端口,这样你就不会危及工作线程.

下面是一个示例,说明这种异步控制器在您的情况下可能如何:

public class HomeController : AsyncController 
{
    public void IndexAsync() 
    {
        AsyncManager.OutstandingOperations.Increment();
        sdk.Items().GetAll(items => 
        {
            decimal price = items.Sum(i => i.Price); 
            AsyncManager.Parameters["price"] = price;
            AsyncManager.OutstandingOperations.Decrement();
        };
    }

    public ActionResult IndexCompleted(decimal price) 
    {
        // Oh Dude, please use view models and crap on this ViewBag shit
        ViewBag.price = price;
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)