Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass information with a WebClient request to identify the object that gets loaded?

I have a collection of custom objects called DataItems which contain URIs of images that I want to load and put in a collection for my Silverlight application to use.

As I process each DataItem, I get its SourceUri (e.g. "http://..../picture001.png") and start it loading:

void LoadNext()
{
    WebClient webClientImgDownloader = new WebClient();
    if (loadedItemIndex < RegisteredDataEntries.Count())
    {
        DataItem dataItem = RegisteredDataEntries[registeredIdCodes[loadedItemIndex]];
        if (dataItem.Kind == DataItemKind.Image)
        {
            webClientImgDownloader.OpenReadCompleted += 
                new OpenReadCompletedEventHandler(webClientImgDownloader_OpenReadCompleted);
            webClientImgDownloader.OpenReadAsync(new Uri(dataItem.SourceUri, 
                UriKind.Absolute));
            webClientImgDownloader.AddObject(dataItem); //????????????????????
            webClientImgDownloader.Headers["idCode"] = dataItem.IdCode; //?????????????
            webClientImgDownloader.ResponseHeaders["idCode"] = dataItem.IdCode; //?????????????
        }
    }
    else
    {
        OnLoadingComplete(this, null);
    }
}

Then when the loading of that image has completed, I save the image in a collection:

void webClientImgDownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    dataItemIdCode = e.DataItem.IdCode; //???????????????????
    dataitemIdCode = ((DataItem)sender).IdCode; //?????????????????????

    BitmapImage bitmap = new BitmapImage();
    bitmap.SetSource(e.Result);

    Image image = new Image();
    image.Source = bitmap;
    Images.Add(dataItemIdCode, image);
}

But how do I pass the IdCode of the current DataItem through to my OpenReadCompleted method so that when that image has completed loading, I can also IDENTIFY it according to its IdCode?

ANSWER:

Franci's suggestion works, here are the lines for anyone else looking for this::

webClientImgDownloader.OpenReadAsync(new Uri(dataItem.SourceUri, 
    UriKind.Absolute), dataItem);
...
DataItem dataItem = e.UserState as DataItem;
like image 436
Edward Tanguay Avatar asked Mar 09 '10 17:03

Edward Tanguay


1 Answers

There's an OpenDataAsync overload that takes a user token object. You should get this object in the OpenReadCompletedEventArgs, in the UserState property (inherited from AsyncCompletedEventArgs).

like image 128
Franci Penov Avatar answered Oct 21 '22 10:10

Franci Penov