我認爲使用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