C#如果超过2秒钟,如何停止方法?

前端之家收集整理的这篇文章主要介绍了C#如果超过2秒钟,如何停止方法?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下程序将连接到网络并获取“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");
        }
    }
原文链接:https://www.f2er.com/csharp/98101.html

猜你在找的C#相关文章