oopbase
oopbase

Reputation: 11395

WebClient doesn't seem to work?

I've got the following code:

WebClient client = new WebClient();
client.OpenReadAsync(new Uri("whatever"));
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);

and:

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  Stream reply = (Stream)e.Result;
  StreamReader s;
  s = new StreamReader(reply);
  this._code = s.ReadToEnd();
  s.Close();
}

While debugging I can see the compiler doesn't move into the client_OpenReadCompleted event. Where's the mistake? I already tried using DownloadStringCompleted and DownloadStringAsync instead, but this doesn't work either.

Thanks for your help.

Upvotes: 3

Views: 3299

Answers (3)

GeertvdC
GeertvdC

Reputation: 2918

I would advice you to not use the WebClient since this has a negative impact on your UI because the callback will always return on the UI thread because of a bug.

Here is explained why and how you can use HttpWebRequest as an alternative

http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/594e1422-3b69-4cd2-a09b-fb500d5eb1d8

Upvotes: 0

as-cii
as-cii

Reputation: 13019

Try to put the event handler before you call the async method.

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("www.google.it"));

EDIT: I have tested this snippet inside LINQPad and it works for me.

void Main()
{
    var client = new System.Net.WebClient();
    client.OpenReadCompleted += (sender, e) =>
    {
        "Read successfully".Dump();
    };
    client.OpenReadAsync(new Uri("http://www.google.it"));
    Console.ReadLine();
}

Are you sure there is no exception inside your code?

Upvotes: 1

Ed Charbeneau
Ed Charbeneau

Reputation: 4634

Your order of operations is incorrect.

//create an instance of webclient
WebClient client = new WebClient();
//assign the event handler
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
//call the read method
client.OpenReadAsync(new Uri("whatever"));

Upvotes: 1

Related Questions