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

2019-06-19 12:57发布

问题:

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

回答1:

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


回答2:

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



回答3:

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


回答4:

You can use the TimeOut property on HttpWebRequest



回答5:

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.



标签: c# timer