我认为使用AsyncControllers将帮助你在这里,因为他们卸载请求线程的处理。
我会用这样的事情(使用作为this article描述的事件模式):
public class MyAsyncController : AsyncController
{
// The async framework will call this first when it matches the route
public void MyAction()
{
// Set a default value for our result param
// (will be passed to the MyActionCompleted method below)
AsyncManager.Parameters["webClientResult"] = "error";
// Indicate that we're performing an operation we want to offload
AsyncManager.OutstandingOperations.Increment();
var client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
if (!e.Cancelled && e.Error == null)
{
// We were successful, set the result
AsyncManager.Parameters["webClientResult"] = e.Result;
}
// Indicate that we've completed the offloaded operation
AsyncManager.OutstandingOperations.Decrement();
};
// Actually start the download
client.DownloadStringAsync(new Uri("http://www.apple.com"));
}
// This will be called when the outstanding operation(s) have completed
public ActionResult MyActionCompleted(string webClientResult)
{
ViewData["result"] = webClientResult;
return View();
}
}
并确保你安装你需要的任何途径,例如(在Global.asax.cs中):
public class MvcApplication : System.Web.HttpApplication
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapAsyncRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
}
}
有没有办法给webclient异步调用添加超时? – 2011-04-19 15:55:39
只是一个说明,看起来这个答案在09年发布在MVC 1.0的日子里。现在使用MVC 2/3,答案略有不同。 MapAsyncRoute方法已消失,不再需要。此外,MyAction方法现在需要重命名为MyActionAsync。否则,一切都以同样的方式工作。 – BFree 2011-06-16 21:41:57