首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在ASP.NET MVC中异步使用WebClient?

在ASP.NET MVC中异步使用WebClient?
EN

Stack Overflow用户
提问于 2009-08-08 15:43:30
回答 2查看 8.8K关注 0票数 8

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

目前我使用的是同步运行的DownloadString方法。我遇到了外部web服务没有响应的问题,这导致我的整个ASP.NET应用程序线程匮乏,没有响应。

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

谢谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-08-09 05:10:08

我认为在这里使用AsyncControllers会对您有所帮助,因为它们可以将处理负载从请求线程中卸载出来。

我会使用类似这样的东西(使用this article中描述的事件模式):

代码语言:javascript
运行
复制
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中):

代码语言:javascript
运行
复制
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 = "" }
        );
    }
}
票数 7
EN

Stack Overflow用户

发布于 2009-08-08 16:00:11

DownloadStringAsync方法使用事件模型,并在完成时引发DownloadStringCompleted。如果请求耗时太长,也可以通过调用WebClient.CancelAsync()来停止请求。这将使您的主请求线程和您的WebClient线程并行运行,并允许您确定希望主线程在返回之前等待多长时间。

在下面的示例中,我们启动下载并设置完成时要调用的事件处理程序。DownloadStringAsync会立即返回,因此我们可以继续处理请求的其余部分。

为了演示对此操作的更细粒度的控制,当我们到达控制器操作的末尾时,我们可以检查下载是否已经完成;如果没有,再等3秒钟,然后中止。

代码语言:javascript
运行
复制
string downloadString = null;

ActionResult MyAction()
{
    //get the download location
    WebClient client = StartDownload(uri);
    //do other stuff
    CheckAndFinalizeDownload(client);
    client.Dispose();
}

WebClient StartDownload(Uri uri)
{
    WebClient client = new WebClient();
    client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Download_Completed);
    client.DownloadStringAsync(uri);
    return client;
}

void CheckAndFinalizeDownload(WebClient client)
{
    if(this.downloadString == null)
    {
        Thread.Sleep(3000);
    }
    if(this.downloadString == null)
    {
        client.CancelAsync();
        this.downloadString = string.Empty;
    }
}

void Download_Completed(object sender, DownloadStringCompletedEventArgs e)
{
    if(!e.Cancelled && e.Error == null)
    {
        this.downloadString = (string)e.Result;
    }
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1249172

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档