C#为什么DownloadStringAsync不返回结果

时间:2013-07-26 22:19:23

标签: c# webclient

我想要超时= 10秒的下载字符串。这段代码永远转到末尾,我无法理解为什么。

                    wc.DownloadStringCompleted += (ender,args)=>
                    {
                        res = args.Result;
                        var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set\\-Cookie:\\s*([\\w\\-_\\.]+\\s*=\\s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
                        foreach (Match val in cook)
                            cookies += val.Groups[1].Value.Trim() + "; ";
                    };
                    wc.DownloadStringAsync(new System.Uri(url));

                    int msec = 0;
                    while (String.IsNullOrEmpty(res))
                    {
                        Thread.Sleep(1);
                        ++msec;
                        if (msec >= 10000)
                        {
                            lastError = "TimeOut";
                            goto theEnd;
                        }
                    }
                    return res;

1 个答案:

答案 0 :(得分:0)

如果您正在使用或可以使用.NET 4.5,请尝试此操作。

var res = wc.DownloadStringAsync(new System.Uri(url)).Result;

// Do whatever work you wanted to do on the result.
var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set\\-Cookie:\\s*([\\w\\-_\\.]+\\s*=\\s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
foreach (Match val in cook)
    cookies += val.Groups[1].Value.Trim() + "; ";
return res;