0

I want download string with timeout=10sec. This code forever goto theEnd, and I can't understand why.

                    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;
4

1 回答 1

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;
于 2013-07-26T22:27:13.340 回答