【发布时间】:2014-05-16 21:01:44
【问题描述】:
我正在开发一个 ASP.NET MVC 5 应用程序。我一直在阅读一些问题here,建议不要使用我想要的行为类型。
我想要达到的高水平 -
MVC 控制器 - 在服务层调用方法,然后继续控制器中的下一行代码,因为不需要返回任何内容。
服务层中的方法 - 我想调用一些具有异步方法的外部 Web 服务,所以我希望这些方法在运行时运行,然后在它们返回时将数据写入数据库。
这样的事情可以实现还是不是最好的方法?
为了模拟这个并测试我在控制器上的原理:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult TestAsync()
{
_myService.TestAsync();
return RedirectToAction("Summary");
}
在 _myService 中,该方法如下所示:
public async Task TestAsync()
{
await Task.Delay(10000);
var test = "Testing";
_testRepository.Add(test);
}
我希望这个 TestAsync 方法会等待 10 秒,然后我可以检查数据库并添加值测试。但是,这不起作用 - 在 UI 上,点击按钮后,页面转到摘要视图,等待 Task.Delay 断点被命中,但下一行永远不会执行。这种方法有什么不正确的吗? TestAsync 方法是否应该看起来像:
public void TestAsync()
{
//Call another private async method here in the class that does the task delay
//which would be similar to calling the actual Async External Web Service methods
var test = "Testing";
_testRepository.Add(test);
}
【问题讨论】:
标签: c# .net asp.net-mvc asynchronous async-await