以下程序将连接到网络并获取“msnbc.com”网页的html内容并打印出结果.如果从网页获取数据需要的时间超过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); } }
解决方法
如上所述.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"); } }