Correlate the completed event to the original WebClient?
I have a WebClient that is fired multiple times in the same class and runs asynchronously. I need a way to correlate the request to the response. Is there a way to, for example, get the original URI in the event completed handler? Or any other way?
开发者_开发技巧I'm using this in silverlight, should you care.
Thanks, Palantir
First off, you can't actually have multiple Asynchronous activities outstanding on the same instance of a WebClient. So I'll assume for the moment that you are creating multiple instances of WebClient and just happen to be assigning the same function to events on these WebClient instances.
Hence simplistically you can correlate the WebClient instance used to generate the request by casting the sender
parameter of the event back to WebClient
.
In addition all the Async methods (on WebClient or on the underlying WebRequest, WebResponse types) wall have an overload that takes an object
userToken. This userToken is the passed on in any subsequent event that arise as a result of the call. You can pass any object you like in the parameter. Hence if you have some other instance of an object or some ID value you would like to use to co-related that call you can this parameter.
WebClient wc = new WebClient();
wc.DownloadStringCompleted += Handle_DownloadStringCompleted;
wc.DownloadString(myUri, myUri);
...
void Handle_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (!e.Canceled)
{
Uri originalUri = (Uri)e.UserState;
// Do stuff with the Uri.
}
}
It's a trade off of performance, but you could use different instances of the WebClient class in which case you'd correlate the response back to the original instance of the WebClient that fired the request.
精彩评论