Reputation: 10950
I want to send a request to a web service and I don't care about the response. The service performs operations in a database--I'm calling it from a simple .NET 4.0 console application that will be set to run on a schedule. This works:
using (var client = new WebClient()) {
client.UseDefaultCredentials = true;
client.DownloadString(uri);
}
but blocks the thread until the response is received. I'd rather do:
using (var client = new WebClient()) {
client.UseDefaultCredentials = true;
client.DownloadStringAsync(uri);
}
but this simply doesn't seem to be sending the request (the database operations are not performed). Is there are really simple solution?
Thanks.
Upvotes: 0
Views: 176
Reputation: 1503310
Yes, the async version will fail as you're disposing of the client immediately.
You could either not dispose of the client:
var client = new WebClient();
client.UseDefaultCredentials = true;
client.DownloadStringAsync(uri);
... or (better) attach an event to dispose of it when it completes:
var client = new WebClient();
client.UseDefaultCredentials = true;
client.DownloadStringCompleted += delegate { client.Dispose(); };
client.DownloadStringAsync(uri);
(You should check whether you need to subscribe to any other events to dispose of it on failure - I can't remember offhand whether the event is still fired in that case.)
Upvotes: 4