Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

timer

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);
    }
}
like image 639
Learner_51 Avatar asked Apr 27 '12 16:04

Learner_51


1 Answers

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

like image 193
Eric Lippert Avatar answered Sep 20 '22 12:09

Eric Lippert