【问题标题】:HttpClient check valid image file asyncHttpClient异步检查有效的图像文件
【发布时间】:2013-08-13 14:18:42
【问题描述】:

我是否误用了 HttpClient 类。我正在尝试测试图像的 HTTP 状态,但它似乎根本没有执行。我有一个复杂对象的列表,所以我想对所有图像 url 运行测试,以查看哪些 url 被破坏:

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 的请求来说非常长。

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • httpclient 上的 GetAsync 不就是这样做的吗?还要把 AsParallel 放在哪里?
    • 我选择了 Parallel.ForEach 但这绝对让我朝着正确的方向前进
    【解决方案2】:

    Linq(通常)是懒惰的。这意味着 Linq 语句仅代表一个查询。当您枚举查询(具体化)时,工作就会发生。

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

    一种方法是简单地调用tasks.ToList()

    【讨论】:

    • 好的,现在看起来它确实在运行,但损坏的 url 没有被替换
    猜你喜欢
    • 1970-01-01
    • 2017-08-31
    • 2010-10-27
    • 2014-11-15
    • 2020-12-04
    • 2019-02-20
    • 1970-01-01
    相关资源
    最近更新 更多