Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
813 views
in Technique[技术] by (71.8m points)

c# - WebClient - wait until file has downloaded

I'm developing a function to return a collection, generated from an xml file.

Initially, I was using a local xml file for testing, but now I'm ready to have the app download the real xml file from a server. I'm struggling to see how I could do this due to the fact a WebClient object needs to be given an OpenReadCompleted event handler - I cannot return the collection data from this, and also by the time this handler executes, the original function has ended.

My original code is as follows:

public static ObservableCollection<OutletViewModel> GetNear(GeoCoordinate location)
{
    ObservableCollection<OutletViewModel> Items = new ObservableCollection<OutletViewModel>();

    // Load a local XML doc to simulate server response for location
    XDocument xDoc = XDocument.Load("SampleRemoteServer/outlet_list.xml");

    foreach (XElement outlet in xDoc.Descendants("outlet"))
    {
        Items.Add(new OutletViewModel()
        {
            Name = outlet.Attribute("name").Value,
            Cuisine = outlet.Attribute("cuisine").Value
        });
    }

    return Items;
}

How can I load the file in this function, have the event handler run, and then continue the function?

The only was I can think of is to add a loop to keep checking a variable, which is updated by the event handler code... and that doesn't sound like a good solution.

Thanks, Josh

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You move the foreach() loop to the completed event.

And that indeed means you cannot return anything from the original method. Make it a void.

This is how async I/O works, better get used to it. You will need to rethink your design.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...