Bing Maps REST服务工具包-代表以外的访问价值 [英] Bing Maps REST Services Toolkit - Access Value Outside of Delegate

查看:67
本文介绍了Bing Maps REST服务工具包-代表以外的访问价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Bing Maps REST服务工具包的此示例代码使用委托获取响应,然后从委托方法中输出消息.但是,它没有演示如何从GetResponse调用之外访问响应.我无法弄清楚如何从此委托返回值.换句话说,让我们说我想在 Console.ReadLine(); 行之前使用 longitude 变量的值?

This sample code for the Bing Maps REST Services Toolkit uses a delegate to get the response and then outputs a message from within the delegate method. However, it does not demonstrate how to access the response from outside of the invocation of GetResponse. I cannot figure out how to return a value from this delegate. In other words, let us say I want to use the value of the longitude variable right before the line Console.ReadLine(); How do I access that variable in that scope?

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using BingMapsRESTToolkit;
    using System.Configuration;
    using System.Net;
    using System.Runtime.Serialization.Json;

    namespace RESTToolkitTestConsoleApp
    {

        class Program
        {

            static private string _ApiKey = System.Configuration.ConfigurationManager.AppSettings.Get("BingMapsKey");

            static void Main(string[] args)
            {
                string query = "1 Microsoft Way, Redmond, WA";

                Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}", query, _ApiKey));

                GetResponse(geocodeRequest, (x) =>
                {
                    Console.WriteLine(x.ResourceSets[0].Resources.Length + " result(s) found.");
                    decimal latitude = (decimal)((Location)x.ResourceSets[0].Resources[0]).Point.Coordinates[0];
                    decimal longitude = (decimal)((Location)x.ResourceSets[0].Resources[0]).Point.Coordinates[1];
                    Console.WriteLine("Latitude: " + latitude);
                    Console.WriteLine("Longitude: " + longitude);
                });
                Console.ReadLine();
            }

            private static void GetResponse(Uri uri, Action<Response> callback)
            {
                WebClient wc = new WebClient();
                wc.OpenReadCompleted += (o, a) =>
                {
                    if (callback != null)
                    {
                        // Requires a reference to System.Runtime.Serialization
                        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
                        callback(ser.ReadObject(a.Result) as Response);
                    }
                };
                wc.OpenReadAsync(uri);
            }
        }
    }

推荐答案

对于所提供的示例 WebClient.OpenReadCompleted 事件像这样完成:

For the provided example AutoResetEvent class could be utilized to control the flow, in particular to wait asynchronous WebClient.OpenReadCompleted Event is completed like this:

class Program
{
    private static readonly string ApiKey = System.Configuration.ConfigurationManager.AppSettings.Get("BingMapsKey");
    private static readonly AutoResetEvent StopWaitHandle = new AutoResetEvent(false);

    public static void Main()
    {
        var query = "1 Microsoft Way, Redmond, WA";
        BingMapsRESTToolkit.Location result = null;

        Uri geocodeRequest = new Uri(string.Format("http://dev.virtualearth.net/REST/v1/Locations?q={0}&key={1}",
            query, ApiKey));
        GetResponse(geocodeRequest, (x) =>
        {
           if (response != null &&
              response.ResourceSets != null &&
              response.ResourceSets.Length > 0 &&
              response.ResourceSets[0].Resources != null &&
              response.ResourceSets[0].Resources.Length > 0)
           {
               result = response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
            }
        });
        StopWaitHandle.WaitOne(); //wait for callback
        Console.WriteLine(result.Point); //<-access result 
        Console.ReadLine();

    }

    private static void GetResponse(Uri uri, Action<Response> callback)
    {
        var wc = new WebClient();
        wc.OpenReadCompleted += (o, a) =>
        {
            if (callback != null)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Response));
                callback(ser.ReadObject(a.Result) as Response);
            }
            StopWaitHandle.Set(); //signal the wait handle
        };
        wc.OpenReadAsync(uri);
    }

}

选项2

或者切换到 ServiceManager类,这使得通过

Or to switch to ServiceManager class that makes it easy when working via asynchronous programming model:

public static void Main()
{
    var task = ExecuteQuery("1 Microsoft Way, Redmond, WA");
    task.Wait();
    Console.WriteLine(task.Result);
    Console.ReadLine();
}

其中

public static async Task<BingMapsRESTToolkit.Location> ExecuteQuery(string queryText)
{
    //Create a request.
    var request = new GeocodeRequest()
        {
            Query = queryText,
            MaxResults = 1,
            BingMapsKey = ApiKey
    };
    //Process the request by using the ServiceManager.
    var response = await request.Execute();
    if (response != null &&
            response.ResourceSets != null &&
            response.ResourceSets.Length > 0 &&
            response.ResourceSets[0].Resources != null &&
            response.ResourceSets[0].Resources.Length > 0)
    {
         return response.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location;
    }
    return null;
}

这篇关于Bing Maps REST服务工具包-代表以外的访问价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆