在阅读了Best Practices in Asynchronous Programming之后,我决定在MVC4中测试死锁行为。从Intranet模板创建网站后,我修改了Index操作,如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace AsyncAwait.MVC4.Controllers
{
public class HomeController : Controller
{
private static async Task DelayAsync()
{
await Task.Delay(1000);
}
// This method causes a deadlock when called in a GUI or ASP.NET context.
public static void Test()
{
// Start the delay.
var delayTask = DelayAsync();
// Wait for the delay to complete.
delayTask.Wait();
}
public ActionResult Index()
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
Test();
return View();
}
}
}如我所料,对Index的调用挂起了,但我也希望在某个时刻抛出一个异常。异常永远不会抛出,所有的请求都会挂起。
我查看了所有可用的性能计数器,但不知道如何识别死锁。如果我要使用一个使用异步/等待的现有网站,我如何设置对潜在死锁的监控?
谢谢!
发布于 2013-04-02 01:57:33
如果你希望你的任务在可预测的时间内完成,那么你可以使用超时。
Task.Wait有几个采用超时值的重载。
例如,如果你的任务不应该超过5秒,你可以这样做。
var delayTask = DelayAsync();
// Will be true if DelayAsync() completes within 5 seconds, otherwise false.
bool callCompleted = delayTask.Wait(TimeSpan.FromSeconds(5));
if (!callCompleted)
{
throw new TimeoutException("Task not completed within expected time.");
}https://stackoverflow.com/questions/15746322
复制相似问题