首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Windows Phone 7: web服务问题

Windows Phone 7: web服务问题
EN

Stack Overflow用户
提问于 2010-09-05 22:04:20
回答 1查看 1.2K关注 0票数 0

在WindowsPhone7应用程序中,我需要通过发送一个"category“字符串参数来查询web服务,并期望得到一个返回的字符串。我尝试遵循MSDN中的"Weather Forecast“示例,但总是得到一个空字符串。如果我添加一些Debug.WriteLine命令,我可以看到回调在返回响应之后执行,也就是说:返回不等待异步操作结束。

我100%地尊重示例代码,有人能看到哪里出了问题吗?代码如下,感谢您的宝贵时间:

代码语言:javascript
复制
    public partial class MainPage : PhoneApplicationPage
{
    // Constructor
    public MainPage()
    {
        InitializeComponent();
    }

    /// <summary>
    /// Event handler to handle when this page is navigated to
    /// </summary>
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        SearchService searchService = new SearchService();
        searchService.GetCategoryCounter("pizza")
        Globals.pizzaCounter = searchService.Counter;    

        searchService.GetCategoryCounter("pasta")
        Globals.pastaCounter = searchService.Counter;

        pizzacounter.Text = Globals.pizzaCounter;
        pastacounter.Text = Globals.pastaCounter;
    }
}

代码语言:javascript
复制
public class SearchService
{

    #region member variables
    private string currentCategoryCount = "";
    public event PropertyChangedEventHandler PropertyChanged;

    #endregion member variables

    #region accessors
    public String Counter
    {
        get
        {
            return currentCategoryCount;
        }
        set
        {
            if (value != currentCategoryCount)
            {
                currentCategoryCount = value;
                NotifyPropertyChanged("Counter");
            }
        }
    }
    #endregion accessors

    #region private Helpers

    /// <summary>
    /// Raise the PropertyChanged event and pass along the property that changed
    /// </summary>
    private void NotifyPropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

    #endregion private Helpers


    /*
    * GetCategoryCounter Method:
    * 
    * @param category
    *            : the category whose counter is to be retrieved
    */
    public void GetCategoryCounter(string category)
    {
        try
        {
            // form the URI
            UriBuilder fullUri = new UriBuilder("http://www.mywebsite.com/items/stats");
            fullUri.Query = "category=" + category;

            // initialize a new WebRequest
            HttpWebRequest counterRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);

            // set up the state object for the async request
            CounterUpdateState counterState = new CounterUpdateState();
            counterState.AsyncRequest = counterRequest;

            // start the asynchronous request
            counterRequest.BeginGetResponse(new AsyncCallback(HandleCounterResponse), counterState);
            return;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    /// <summary>
    /// Handle the information returned from the async request
    /// </summary>
    /// <param name="asyncResult"></param>
    private void HandleCounterResponse(IAsyncResult asyncResult)
    {
        // get the state information
        CounterUpdateState counterState = (CounterUpdateState)asyncResult.AsyncState;
        HttpWebRequest counterRequest = (HttpWebRequest)counterState.AsyncRequest;

        // end the async request
        counterState.AsyncResponse = (HttpWebResponse)counterRequest.EndGetResponse(asyncResult);

        Stream streamResult;
        string currentCount = "";

        try
        {
            // get the stream containing the response from the async call
            streamResult = counterState.AsyncResponse.GetResponseStream();

            StreamReader reader = new StreamReader(streamResult);
            currentCount = reader.ReadToEnd();

            // copy the data over
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                Counter = currentCount;
            });
        }
        catch (FormatException ex)
        {
            throw ex;
        }

    }
}

/// <summary>
/// State information for our BeginGetResponse async call
/// </summary>
public class CounterUpdateState
{
    public HttpWebRequest AsyncRequest { get; set; }
    public HttpWebResponse AsyncResponse { get; set; }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-09-05 22:34:23

你的示例代码甚至不能编译...比较一下:

代码语言:javascript
复制
Globals.pizzaCounter = searchService.GetCategoryCounter("pizza");

有了这个:

代码语言:javascript
复制
public void GetCategoryCounter(string category)

注意它是一个空方法--所以你不能把返回值赋给Globals.pizzaCounter

您需要记住,这是异步发生的。正如您所说的,“如果我添加一些Debug.WriteLine命令,我可以看到回调在返回响应之后执行,也就是说:返回不等待异步操作结束。”这就是异步的全部含义。你不想阻塞你的UI线程等待服务返回。

相反,您应该向您的服务获取代码传递一个回调,以便在您的服务返回一些数据时执行。然后需要通过Dispatcher封送回UI线程,然后才能更新textbox。您的代码已经完成了其中的一些操作,方法是封送回UI线程,然后更新属性,这将引发PropertyChanged事件,让UI知道从属性中重新获取数据。但是,看起来只有一个计数器,而您正在尝试获取两个不同的类别。您可能应该将服务本身从“类别计数器”(或其他任何东西)中分离出来,它知道搜索服务,但也是特定于一个类别的。这样就有了两个实例(但只有一个搜索服务);每个文本框都会绑定到类别计数器的相关实例。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3646308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档