Bhu*_*hah 2 .net c# asp.net-mvc asynchronous asp.net-mvc-4
我正在使用 MVC 4 和 .NET 4.5。我希望利用新的 TAP(异步等待)构建一个异步控制器。我从Controller和 not继承了这个控制器AsyncContoller,因为我使用的是基于任务的异步性,而不是基于事件的异步性。
我有两种操作方法 - 一种同步执行操作,另一种异步执行相同的操作。我的视图中的表单中还有两个提交按钮,每个操作方法一个。
下面是这两种方法的代码:
同步:
[HttpPost]
public ActionResult IndexSync(FormCollection formValues)
{
int Min = Int32.Parse(formValues["txtMin"]);
int Count = Int32.Parse(formValues["txtCount"]);
string Primes;
DateTime started = DateTime.Now;
using (BackendServiceReference.ServiceClient service = new ServiceClient())
{
Primes = service.GetPrimesServiceMethod(Min, Count);
}
DateTime ended = DateTime.Now;
TimeSpan serviceTime = ended - started;
ViewBag.ServiceTime = serviceTime;
ViewBag.Primes = Primes;
return View("Index");
}
Run Code Online (Sandbox Code Playgroud)
异步:
[HttpPost]
public async Task<ActionResult> IndexAsync(FormCollection formValues)
{
int Min = Int32.Parse(formValues["txtMin"]);
int Count = Int32.Parse(formValues["txtCount"]);
string Primes;
Task<string> PrimesTask;
DateTime started = DateTime.Now;
using (BackendServiceReference.ServiceClient service = new ServiceClient())
{
PrimesTask = service.GetPrimesServiceMethodAsync(Min, Count);
}
DateTime ended = DateTime.Now;
TimeSpan serviceTime = ended - started;
ViewBag.ServiceTime = serviceTime;
Primes = await PrimesTask;
ViewBag.Primes = Primes;
return View("Index");
}
Run Code Online (Sandbox Code Playgroud)
在async方法中,我期望DateTime ended = DateTime.Now在service方法被调用后立即执行,而耗时的service方法在后台异步执行。
但是,这不会发生,并且在调用服务方法时执行“等待”,而不是在Primes = await PrimesTask发生的地方等待。
有什么我错过了吗?
朝着正确方向的推动将不胜感激。
我怀疑它实际上是在阻止ServiceClient.Dispose.
要解决此问题,请扩展该using块以包含您的await:
using (BackendServiceReference.ServiceClient service = new ServiceClient())
{
PrimesTask = service.GetPrimesServiceMethodAsync(Min, Count);
DateTime ended = DateTime.Now;
TimeSpan serviceTime = ended - started;
ViewBag.ServiceTime = serviceTime;
Primes = await PrimesTask;
}
ViewBag.Primes = Primes;
Run Code Online (Sandbox Code Playgroud)