加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 04:28:04 所属栏目:asp.Net 来源:网络整理
导读:我有一个ASP.NET MVC应用程序,它当前使用WebClient类从控制器操作中对外部Web服务进行简单调用. 目前我正在使用同步运行的DownloadString方法.我遇到了外部Web服务没有响应的问题,这导致我的整个ASP.NET应用程序都缺乏线程并且没有响应. 解决此问题的最佳方
我有一个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 = "" }
        );
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读