2012-04-27 39 views
6

以下程序將連接到網頁並獲取「msnbc.com」網頁的html內容並打印出結果。如果從網頁獲取數據需要2秒以上的時間,我希望我的方法停止工作並返回。你能告訴我怎麼用一個例子來做這件事?C#如果停止方法的時間超過2秒,該如何停止?

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     gethtml(); 
     MessageBox.Show("End of program"); 
    } 

    public void gethtml() 
    { 
     HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("http://msnbc.com/"); 

     WebResponse Response = WebRequestObject.GetResponse(); 
     Stream WebStream = Response.GetResponseStream(); 

     StreamReader Reader = new StreamReader(WebStream); 
     string webcontent = Reader.ReadToEnd(); 
     MessageBox.Show(webcontent); 
    } 
} 
+3

你可能想執行一個線程讀取,並中止線程,如果它超過兩秒(通過定時器設置/調用)。 – ashes999 2012-04-27 16:20:27

+6

@ ashes999:這是一個非常非常糟糕的主意。 **如果您打算放棄整個過程,請僅中止一個線程。**中止一個線程應該是最後的手段。中止託管線程可以任意破壞數據結構。 – 2012-04-27 16:28:02

+0

非常感謝您的答覆。 – 2012-04-27 16:39:01

回答

4

如上.Timeout

public void gethtml() 
    { 
     HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create("http://msnbc.com/"); 
     WebRequestObject.Timeout = (System.Int32)TimeSpan.FromSeconds(2).TotalMilliseconds; 
     try 
     { 
      WebResponse Response = WebRequestObject.GetResponse(); 
      Stream WebStream = Response.GetResponseStream(); 

      StreamReader Reader = new StreamReader(WebStream); 
      string webcontent = Reader.ReadToEnd(); 
      MessageBox.Show(webcontent); 
     } 
     catch (System.Net.WebException E) 
     { 
      MessageBox.Show("Fail"); 
     } 
    } 
+0

非常感謝您向我展示一個例子。 – 2012-04-27 16:38:47

6

設置你的WebRequest對象的Timeout財產。 Documentation

MSDN例子:

// Create a new WebRequest Object to the mentioned URL. 
WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com"); 
Console.WriteLine("\nThe Timeout time of the request before setting is : {0} milliseconds",myWebRequest.Timeout); 

// Set the 'Timeout' property in Milliseconds. 
myWebRequest.Timeout=10000; 

// This request will throw a WebException if it reaches the timeout limit before it is able to fetch the resource. 
WebResponse myWebResponse=myWebRequest.GetResponse(); 
+0

+1。使用它時不要忘記處理超時異常。 – 2012-04-27 16:24:13

0

考慮切換到內容的異步下載。您將停止阻止UI線程,並能夠輕鬆處理多個請求。您將能夠在不影響用戶界面的情況下顯着增加超時時間,並且如果您仍然想要獲取數據,可以決定接收響應。

12

兩秒陳述是太久阻止的UI。如果您打算獲得結果,例如50毫秒或更短,您應該只阻止用戶界面。

閱讀這篇文章,就如何做一個網絡請求,而不阻塞UI:

http://www.developerfusion.com/code/4654/asynchronous-httpwebrequest/

注意,這都將是C#5,這是測試版目前要容易得多。在C#5中,您可以簡單地使用await運算符來異步等待任務的結果。如果您想怎麼看這樣的事情會工作在C#5,請參閱:

http://msdn.microsoft.com/en-us/async