我有一个ASP.NET MVC应用程序,它当前使用WebClient类从控制器操作中对外部web服务进行简单的调用。
目前我使用的是同步运行的DownloadString方法。我遇到了外部web服务没有响应的问题,这导致我的整个ASP.NET应用程序线程匮乏,没有响应。
解决此问题的最佳方法是什么?有一个DownloadStringAsync方法,但我不确定如何从控制器调用它。我需要使用AsyncController类吗?如果是这样,AsyncController和DownloadStringAsync方法是如何交互的呢?
谢谢你的帮助。
发布于 2009-08-09 05:10:08
我认为在这里使用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 = "" }
);
}
}发布于 2009-08-08 16:00:11
DownloadStringAsync方法使用事件模型,并在完成时引发DownloadStringCompleted。如果请求耗时太长,也可以通过调用WebClient.CancelAsync()来停止请求。这将使您的主请求线程和您的WebClient线程并行运行,并允许您确定希望主线程在返回之前等待多长时间。
在下面的示例中,我们启动下载并设置完成时要调用的事件处理程序。DownloadStringAsync会立即返回,因此我们可以继续处理请求的其余部分。
为了演示对此操作的更细粒度的控制,当我们到达控制器操作的末尾时,我们可以检查下载是否已经完成;如果没有,再等3秒钟,然后中止。
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;
}
}https://stackoverflow.com/questions/1249172
复制相似问题