C#如果它超过2秒时间较长如何停止的方法? [英] C# How to stop a method if it takes longer than 2 seconds?

查看:275
本文介绍了C#如果它超过2秒时间较长如何停止的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序将连接到网络,并获得msnbc.com网页的HTML内容并打印出结果。如果需要超过2秒,从网页中获取数据,我想我的方法停止工作,并返回。你能告诉我,我怎么可以这样用一个例子?

 公共部分Form1类:表格
{
公共Form1中()
{
的InitializeComponent();
}

私人无效的button1_Click(对象发件人,EventArgs五)
{
gethtml();
MessageBox.Show(程序结束);
}

公共无效gethtml()
{
HttpWebRequest的WebRequestObject =(HttpWebRequest的)HttpWebRequest.Create(http://msnbc.com/);

WebResponse的响应= WebRequestObject.GetResponse();
流WebStream = Response.GetResponseStream();

StreamReader的读者=新的StreamReader(WebStream);
串的WebContent = Reader.ReadToEnd();
MessageBox.Show(的WebContent);
}
}


解决方案

由于上述.Timeout说

 公共无效gethtml()
{
HttpWebRequest的WebRequestObject =(HttpWebRequest的)HttpWebRequest的。创建(http://msnbc.com/);
WebRequestObject.Timeout =(System.Int32)TimeSpan.FromSeconds(2).TotalMilliseconds;

{
WebResponse的响应= WebRequestObject.GetResponse();
流WebStream = Response.GetResponseStream();

StreamReader的读者=新的StreamReader(WebStream);
串的WebContent = Reader.ReadToEnd();
MessageBox.Show(的WebContent);
}
赶上(System.Net.WebException E)
{
MessageBox.Show(失败);
}
}


Following program will connect to the web and get html content of "msnbc.com" webpage and print out the result. If it takes longer than 2 seconds to get data from the webpage, I want my method to stop working and return. Can you please tell me how can I do this with an example?

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);
    }
}

解决方案

As stated above .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");
        }
    }

这篇关于C#如果它超过2秒时间较长如何停止的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆