【发布时间】:2012-02-22 15:53:08
【问题描述】:
所以我正试图了解 .net 4.5 中的这个新的“异步”内容。我之前玩了一点异步控制器和任务并行库,最后得到了这段代码:
拿这个模型:
public class TestOutput
{
public string One { get; set; }
public string Two { get; set; }
public string Three { get; set; }
public static string DoWork(string input)
{
Thread.Sleep(2000);
return input;
}
}
在这样的控制器中使用:
public void IndexAsync()
{
AsyncManager.OutstandingOperations.Increment(3);
Task.Factory.StartNew(() =>
{
return TestOutput.DoWork("1");
})
.ContinueWith(t =>
{
AsyncManager.OutstandingOperations.Decrement();
AsyncManager.Parameters["one"] = t.Result;
});
Task.Factory.StartNew(() =>
{
return TestOutput.DoWork("2");
})
.ContinueWith(t =>
{
AsyncManager.OutstandingOperations.Decrement();
AsyncManager.Parameters["two"] = t.Result;
});
Task.Factory.StartNew(() =>
{
return TestOutput.DoWork("3");
})
.ContinueWith(t =>
{
AsyncManager.OutstandingOperations.Decrement();
AsyncManager.Parameters["three"] = t.Result;
});
}
public ActionResult IndexCompleted(string one, string two, string three)
{
return View(new TestOutput { One = one, Two = two, Three = three });
}
得益于 TPL 的魔力,此控制器在 2 秒内呈现视图。
现在我预计(相当天真)上面的代码会使用 C# 5 的新“异步”和“等待”功能转换为以下代码:
public async Task<ActionResult> Index()
{
return View(new TestOutput
{
One = await Task.Run(() =>TestOutput.DoWork("one")),
Two = await Task.Run(() =>TestOutput.DoWork("two")),
Three = await Task.Run(() =>TestOutput.DoWork("three"))
});
}
此控制器在 6 秒 内呈现视图。在翻译的某个地方,代码变得不再平行。我知道异步和并行是两个不同的概念,但不知何故,我认为代码的工作方式相同。有人能指出这里发生了什么以及如何解决吗?
【问题讨论】:
-
所以基本上我混合了异步性和并行性。我(错误地)认为最终使用任务的结果时会发生实际的等待(与仅在枚举时执行 linq 查询不同)。
标签: asp.net-mvc asynchronous task-parallel-library