C#为什么下载StringAsync don';t返回结果

本文关键字:返回 结果 为什么 下载 StringAsync don | 更新日期: 2023-09-27 18:25:04

我想要超时为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;

C#为什么下载StringAsync don';t返回结果

如果您正在使用或可以使用.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;