我有一个ASP.NET MVC应用程序,它当前使用WebClient类从控制器操作中对外部web服务进行简单的调用。
目前我使用的是同步运行的DownloadString方法。我遇到了外部web服务没有响应的问题,这导致我的整个ASP.NET应用程序线程匮乏,没有响应。
解决此问题的最佳方法是什么?有一个DownloadStringAsync方法,但我不确定如何从控制器调用它。我需要使用AsyncController类吗?如果是这样,AsyncController和DownloadStringAsync方法是如何交互的呢?
谢谢你的帮助。
发布于 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
复制相似问题