一千萬個為什麽

搜索

c#如何使Sure Webclient允許下載所需的時間

using (var client = new WebClient())
                {
                     html = client.DownloadString(some_string);
                     //do something
                     html = client.DownloadString(some_string1);
                     //do something
html = client.DownloadString(some_string2);
                     //do something
html = client.DownloadString(some_string3);
                     //do something
etc
                }

webclient不允許自己有足夠的時間下載整個網頁源。我怎麽強迫它等到它完成下載?

最佳答案

DownloadString是一個阻塞調用,所以不需要做任何事情。它將繼續下載,直到收到字符串。

問題可能在於您不應該使用DownloadString。你想要檢索什麽?你最終得到了預期字符串的一半嗎?

您可能應該使用它作為MSDN文章顯示:

WebClient client = new WebClient ();

// Add a user agent header in case the 
// requested URI contains a query.

client.Headers.Add ("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");

Stream data = client.OpenRead (some_string);
StreamReader reader = new StreamReader (data);
string s = reader.ReadToEnd ();
Console.WriteLine (s);
data.Close ();
reader.Close ();

The source is here: http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.80).aspx

轉載註明原文: c#如何使Sure Webclient允許下載所需的時間