0

So basiacally, I'm creating a dll project which have to get some info from the bing maps api. Below I'm pasting a method which is resposible for getting and serializing the response:

private void GetResponse(Uri uri, Action<Response> callback)
    {
        WebClient wc = new WebClient();
        wc.OpenReadCompleted += (o, a) =>
        {
            if (callback != null)
            {
                DataContractJsonSerializer responseSerializer = new DataContractJsonSerializer(typeof(Response));
                callback(responseSerializer.ReadObject(a.Result) as Response);
            }
        };
        wc.OpenReadAsync(uri);
    }

Below method is using GetResponse method to get lattitudes:

public Lattitudes getLattitudes()
    {
        Lattitudes lattitudes = new Lattitudes();
        GetResponse(geocodeRequestURI, (x) =>
        {
            lattitudes.SouthLatitude = x.ResourceSets[0].Resources[0].BoundingBox[0];
            lattitudes.SouthLatitude = x.ResourceSets[0].Resources[0].BoundingBox[1];
            lattitudes.SouthLatitude = x.ResourceSets[0].Resources[0].BoundingBox[2];
            lattitudes.SouthLatitude = x.ResourceSets[0].Resources[0].BoundingBox[3];
        });
        return lattitudes;
    } 

My problem is that second method is returning empty object and part inside GetResponse method is being executed later. Is There a way to wait for this event to finish and then return, or maybe I need to redesign it ?(max version of .NET I can use is 4.0)

MajkeloDev
  • 1,661
  • 13
  • 30

1 Answers1

3

I suggest if you want to wait than make use of Task by converting method competable with async and await like as below

private async Task RequestDataAsync(string uri, Action<string> action)
{
    var client = new WebClient();
    string data = await client.OpenReadAsync(uri);
    action(data);
}

call method from the code

   Task t = RequestDataAsync(parameter)
   t.Wait();

this help more : http://www.dotnetperls.com/async

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263