asp.net-mvc – 异步使用ASP.NET MVC中的WebClient?

我有一个ASP.NET MVC应用程序,它当前使用WebClient类从控制器操作中对外部Web服务进行简单调用.

目前我正在使用同步运行的DownloadString方法.我遇到了外部Web服务没有响应的问题,这导致我的整个ASP.NET应用程序都缺乏线程并且没有响应.

解决此问题的最佳方法是什么?有一个DownloadStringAsync方法,但我不确定如何从控制器调用它.我需要使用AsyncController类吗?如果是这样,AsyncController和DownloadStringAsync方法如何交互?

谢谢您的帮助.

解决方法

我认为使用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 = "" }
        );
    }
}

相关文章

这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...
最近用到了CalendarExtender,结果不知道为什么发生了错位,...
ASP.NET 2.0 page lifecyle ASP.NET 2.0 event sequence cha...