C# How to stop a method if it takes longer than 2

2019-06-19 13:15发布

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

标签: c# timer
5条回答
乱世女痞
2楼-- · 2019-06-19 13:22

Set the Timeout property of your WebRequest object. Documentation

MSDN Example:

// 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();
查看更多
甜甜的少女心
3楼-- · 2019-06-19 13:23

You can use the TimeOut property on HttpWebRequest

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2019-06-19 13:28

Consider switching to asynchronous downloading of the content. You will stop blocking UI thread and will be able to handle multiple requests easily. You will be able to increase timeout significantly without impact on UI, and can decide upon receiving response if you still want to fetch data.

查看更多
狗以群分
5楼-- · 2019-06-19 13:36

Two seconds is far too long to block the UI. You should only block the UI if you are planning on getting the result in, say fifty milliseconds or less.

Read this article on how to do a web request without blocking the UI:

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

Note that this will all be much easier in C# 5, which is in beta release at present. In C# 5 you can simply use the await operator to asynchronously await the result of the task. If you would like to see how this sort of thing will work in C# 5, see:

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

查看更多
萌系小妹纸
6楼-- · 2019-06-19 13:43

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");
        }
    }
查看更多
登录 后发表回答