我正在阅读很多文章并看过mvc项目的例子,但是我的问题找不到答案,请帮帮我。
问题: 我有异步mvc5应用程序的简单示例,但我不明白发生什么情况下划线,哪个版本是正确的,为什么?十分感谢。
示例
public class HomeController : Controller
{
[HttpGet]
public async Task<JsonResult> NamesAsync()
{
var result = await new TestService().GetNamesAsync();
return Json(result,JsonRequestBehavior.AllowGet);
}
public async Task<JsonResult> Names()
{
var result = await new TestService().GetName();
return Json(result, JsonRequestBehavior.AllowGet);
}
}
public sealed class TestService
{
public async Task<List<string>> GetNamesAsync()
{
return await new DataLayer().GetNamesAsync();
}
public Task<List<string>> GetName()
{
return Task<List<string>>.Factory.StartNew(() => new DataLayer().GetNames());
}
}
public sealed class DataLayer
{
public async Task<List<string>> GetNamesAsync()
{
using (var context = new TestContext())
{
return await context.Names.Select(x => x.NameText).ToListAsync();
}
}
public List<string> GetNames()
{
var tcs = new TaskCompletionSource<List<string>>();
Task.Factory.StartNew(() =>
{
using (var context = new TestContext())
{
var names = context.Names.Select(x => x.NameText).ToList();
tcs.SetResult(names);
}
});
Task.WhenAll(tcs.Task);
return tcs.Task.Result;
}
}
答案 0 :(得分:0)
异步代码的一条规则是“不要让你的代码撒谎”。有些操作(特别是I / O)本质上是异步的,它们应该公开异步API。
数据库受I / O约束,因此它们属于自然异步类别:
public class HomeController : Controller
{
[HttpGet]
public async Task<JsonResult> NamesAsync()
{
var result = await new TestService().GetNamesAsync();
return Json(result,JsonRequestBehavior.AllowGet);
}
}
public sealed class TestService
{
public async Task<List<string>> GetNamesAsync()
{
return await new DataLayer().GetNamesAsync();
}
}
public sealed class DataLayer
{
public async Task<List<string>> GetNamesAsync()
{
using (var context = new TestContext())
{
return await context.Names.Select(x => x.NameText).ToListAsync();
}
}
}