Luzius L
Luzius L

Reputation: 157

WebClient Callback Async-Result?

I would like to write a class which has handles my WebClient-Tasks and returns its results.
The problem is, that async downloads won't let a simple return handle:

public void checkAvailability()
{
     WebClient wc = new WebClient();
     wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
     wc.UploadStringCompleted += wc_UploadStringCompleted;
     wc.UploadStringAsync(new Uri("http://random.php"), "?lookup=10");

     //return parsed content from wc_UploadStringCompleted
}

private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
     // do something
}

How can I put it all together to make it work?

Upvotes: 2

Views: 5962

Answers (2)

rodmanwu
rodmanwu

Reputation: 1

usse UploadStringTaskAsync indeed a better choice!

string data = "lookup=10";
string json = await WebClient.UploadStringTaskAsync(Uri, data);

the post data don't need "?"

Upvotes: 0

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14328

OK, with Visual Studio 2012 and .NET 4.5 it's easier to use the UploadStringTaskAsync() method from the System.Net.WebClient class:

public async Task<string> CheckAvailability()
{
    var webClient = new WebClient();
    webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    var result = await webClient.UploadStringTaskAsync(new Uri("http://random.php"), "?lookup=10");
    return result;
}

Any exception thrown by the method will interrupt your application flow like a regular, non-asynchronous method. Do note though that you have to await for this method wherever you call it to get the result, too, so:

var availability = await CheckAvailability();

in some other async marked method.

If you don't want to use this, you have to use callbacks:

public void CheckAvailability(Action<Exception, string> callback)
{
    var webClient = new WebClient();
    webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
    webClient.UploadStringCompleted += (s,e) => { 
                                                    if(e.Error != null)
                                                        callback(e.Error, string.Empty);
                                                    else
                                                        callback(null, e.Result);
                                                };
    wc.UploadStringAsync(new Uri("http://random.php"), "?lookup=10");
}

Now you have to pass the function returning void and taking two parameters of type Exception and string that will execute when the upload is finished, but you have to handle exceptions manually.

Upvotes: 3

Related Questions