AsyncControllerを使用すると、リクエストスレッドからの処理をオフロードする際に役立ちます。
私は(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非同期呼び出しにタイムアウトを追加する方法はありますか? –
ちょっとメモしておけば、この回答はMVC 1.0で09年に掲載されたようです。 MVC 2/3では答えはちょっと違います。 MapAsyncRouteメソッドがなくなり、不要になりました。また、MyActionメソッドの名前をMyActionAsyncに変更する必要があります。それ以外の場合は、すべて同じように動作します。 – BFree