The application crashes when I try to get the URL content

advertisements

First see my Source Code:

WebClient client = new WebClient();
String url = "http://localhost";
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
try
{
    Stream data = client.OpenRead(url);
    if (data == null)
        throw new WebException("Cannot browse the url...");
    StreamReader reader = new StreamReader(data);
    string s = reader.ReadToEnd();
    textBox1.Text = s;
    data.Close();
    reader.Close();

}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

When I run my application, It will freeze in the duration of this operation.
Which part of my code is wrong?


Which part of my code is wrong?

The part where you perform a blocking network operation in your UI thread. While your UI thread is blocked waiting for the response, the controls can't repaint and your UI can't respond to events.

You should do this in a background thread and then use Control.Invoke (WinForms) or Dispatcher.Invoke (WPF) to marshal a call back to the UI thread. See Joe Albahari's threading guide for more information.

Alternatively, use the async operations on WebClient.