HttpClient检查有效的图像文件异步

时间:2013-08-13 14:18:43

标签: c# asynchronous asp.net-mvc-2 httpclient

我是否错误地滥用了HttpClient类。我试图测试图像的HTTP状态,它似乎根本没有执行。我有一个复杂对象的列表,所以我想在所有图片网址上运行测试,看看哪些网址被破坏了:

var client = new HttpClient();
var tasks = ObjectViewModel.Select(a => a.UserUrl).Select(url =>   
client.GetAsync(url).ContinueWith(t =>
{
  var response = t.Result;
   if (!response.IsSuccessStatusCode)
   url = "/Content/Images/MissingPic.png";
 }));

我最初在foreach循环中这样做:

foreach(var Model in ObjectViewModel)
{
 Model.UserUrl= Model.UserUrl.GetHttpRequest() ? Model.UserUrl: 
"/Content/Images/MissingImage.png";
 //Model.state= Model.state.ValidName();// this line is something seperate
 //Model.property= Model.state.propertyCheck();// this line is something seperate

}

public static bool GetHttpRequest(this string s)
{
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest
                                       .Create(s);
        webRequest.AllowAutoRedirect = false;
        HttpStatusCode responseStatusCode;

        try
        {
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            responseStatusCode = response.StatusCode;
        }
        catch (WebException we)
        {
            responseStatusCode = ((HttpWebResponse)we.Response).StatusCode;
        }
        if (responseStatusCode.ToString() == "OK")
            return true;
        else
            return false;
}

完全正常,但需要大约5到7秒才能完成所有项目,因为它们都是单独运行的,这对于响应UI的请求来说非常长。

2 个答案:

答案 0 :(得分:1)

在迭代枚举时考虑使用AsParallel(),应该大大加快它的速度。

var UrlToReponseMap = new Dictionary<string, bool>();
ObjectViewModel.AsParallel().ForAll(x =>
{
  UrlToReponseMap[x.UserUrl] = x.UserUrl.GetHttpRequest();
});

答案 1 :(得分:0)

Linq(一般)懒惰。这意味着Linq语句仅代表查询。枚举查询(实现)时会发生工作。

您永远不会实现tasks查询。要使它实际运行select语句中的代码,您需要通过使查询枚举来实现查询。

一种方法是简单地拨打tasks.ToList()