asp.net-mvc – MVC4异步和并行执行

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – MVC4异步和并行执行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我试图让我的头脑围绕这个新的“异步”东西在.net 4.5.我以前玩异步控制器和任务并行库,并清理了这段代码

采取这种模式:

  1. public class TestOutput
  2. {
  3. public string One { get; set; }
  4. public string Two { get; set; }
  5. public string Three { get; set; }
  6.  
  7. public static string DoWork(string input)
  8. {
  9. Thread.Sleep(2000);
  10. return input;
  11. }
  12. }

在这样的控制器中使用哪一个:

  1. public void IndexAsync()
  2. {
  3. AsyncManager.OutstandingOperations.Increment(3);
  4.  
  5. Task.Factory.StartNew(() =>
  6. {
  7. return TestOutput.DoWork("1");
  8. })
  9. .ContinueWith(t =>
  10. {
  11. AsyncManager.OutstandingOperations.Decrement();
  12. AsyncManager.Parameters["one"] = t.Result;
  13. });
  14. Task.Factory.StartNew(() =>
  15. {
  16. return TestOutput.DoWork("2");
  17. })
  18. .ContinueWith(t =>
  19. {
  20. AsyncManager.OutstandingOperations.Decrement();
  21. AsyncManager.Parameters["two"] = t.Result;
  22. });
  23. Task.Factory.StartNew(() =>
  24. {
  25. return TestOutput.DoWork("3");
  26. })
  27. .ContinueWith(t =>
  28. {
  29. AsyncManager.OutstandingOperations.Decrement();
  30. AsyncManager.Parameters["three"] = t.Result;
  31. });
  32. }
  33.  
  34. public ActionResult IndexCompleted(string one,string two,string three)
  35. {
  36. return View(new TestOutput { One = one,Two = two,Three = three });
  37. }

由于TPL的魔力,该控制器会在2秒内呈现视图.

现在,我预计(相当天真地),上面的代码将转换为以下内容,使用C#5的新“异步”和“等待”功能

  1. public async Task<ActionResult> Index()
  2. {
  3. return View(new TestOutput
  4. {
  5. One = await Task.Run(() =>TestOutput.DoWork("one")),Two = await Task.Run(() =>TestOutput.DoWork("two")),Three = await Task.Run(() =>TestOutput.DoWork("three"))
  6. });
  7. }

该控制器在6秒内呈现视图.在翻译的某个地方,代码变得不再平行.我知道异步和并行是两个不同的概念,但不知何故我认为代码将工作相同.有人可以指出这里发生了什么,如何解决

解决方法

Somewhere in the translation the code became no longer parallel.

恰恰.等待(异步)等待单个操作完成.

并行异步操作可以通过启动实际的任务来完成,但不等待它们直到以后:

  1. public async Task<ActionResult> Index()
  2. {
  3. // Start all three operations.
  4. var tasks = new[]
  5. {
  6. Task.Run(() =>TestOutput.DoWork("one")),Task.Run(() =>TestOutput.DoWork("two")),Task.Run(() =>TestOutput.DoWork("three"))
  7. };
  8.  
  9. // Asynchronously wait for them all to complete.
  10. var results = await Task.WhenAll(tasks);
  11.  
  12. // Retrieve the results.
  13. return View(new TestOutput
  14. {
  15. One = results[0],Two = results[1],Three = results[2]
  16. });
  17. }

附:还有一个Task.WhenAny.

猜你在找的asp.Net相关文章