Bri*_*nga 8 asp.net-mvc multithreading asynchronous webclient
我有一个ASP.NET MVC应用程序,它当前使用WebClient类从控制器操作中对外部Web服务进行简单调用.
目前我正在使用同步运行的DownloadString方法.我遇到了外部Web服务没有响应的问题,这导致我的整个ASP.NET应用程序都缺乏线程并且没有响应.
解决此问题的最佳方法是什么?有一个DownloadStringAsync方法,但我不确定如何从控制器调用它.我需要使用AsyncController类吗?如果是这样,AsyncController和DownloadStringAsync方法如何交互?
谢谢您的帮助.
我认为使用AsyncControllers可以帮助你,因为他们从请求线程卸载处理.
我会用这样的事情(使用作为中描述的事件模式这篇文章):
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();
}
}
Run Code Online (Sandbox Code Playgroud)
并确保您设置所需的任何路由,例如(在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 = "" }
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8212 次 |
| 最近记录: |